首页 > 解决方案 > 具有 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 ?? []
}

任何提示或指针将不胜感激。

标签: swiftpush-notificationclosuresuilocalnotificationcompletionhandler

解决方案


您可能可以使用如下的调度组。您实际上在做的是等待从线程中检索所有通知,然后继续



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
}

推荐阅读