swift - 具有 UNNotificationRequest 的计算属性返回无法将类型“Void”的返回表达式转换为返回类型“[UNNotificationRequest]”
问题描述
我有一个处理本地通知的类,我想根据是否已安排任何通知来确定它们是否已启用。所以我想我可以尝试创建一个包含所有计划通知数组的计算属性,但我认为有些东西我不明白,因为我收到以下错误:
无法将类型“Void”的返回表达式转换为返回类型“[UNNotificationRequest]”
var notifications: [UNNotificationRequest] {
center.getPendingNotificationRequests { notifications in return notifications }
}
只需从完成处理程序中打印通知就可以了,因此我能够正确获取它们,而不是将它们分配给变量。
我还尝试创建一个单独的变量并返回它,但这始终默认为我提供的空默认值。
var notifications: [UNNotificationRequest] {
var retrievedNotifications: [UNNotificationRequest]?
center.getPendingNotificationRequests { notifications in retrievedNotifications = notifications }
return retrievedNotifications ?? []
}
任何提示或指针将不胜感激。
解决方案
您可能可以使用如下的调度组。您实际上在做的是等待从线程中检索所有通知,然后继续
var notifications: [UNNotificationRequest] {
var retrievedNotifications: [UNNotificationRequest] = []
let group = DispatchGroup()
group.enter()
// avoid deadlocks by not using .main queue here
DispatchQueue.global(attributes: .qosDefault).async {
center.getPendingNotificationRequests { notifications in
retrievedNotifications = notifications
group.leave()
}
}
// wait ...
group.wait()
return retrievedNotifications
}
推荐阅读
- node.js - Redis 节点监听 SET 事件并为每个请求设置一个 TTL
- reactjs - 如何通过get方法在每个输入字段中设置状态值
- azure - 将文件从远程桌面 (RDP) 复制到 Azure Blob 存储
- python-3.x - 烧瓶 | JINJA 2:在上下文中导入宏的 render_template_string()
- swift - 真的不知道如何设置功能以识别单元格是否被选中
- c - 获取鼠标按钮状态非阻塞linux
- sql - Laravel updateOrCreate on hasOne 具有不同值的关系
- python - 获取 pymongo.errors.CursorNotFound: cursor id "..." not found
- javascript - 为什么我的 Firestore 权限不起作用?
- python - 按键过滤字典