带有 UNNotificationRequest 返回的计算属性 不能将类型为 'Void' 的返回表达式转换为类型为 '[UNNotificationRequest]' 的返回。

问题描述 投票:0回答:1

我有一个处理本地通知的类,我想根据是否有任何通知被调度来确定它们是否被启用。因此,我想我可以尝试创建一个计算属性,该属性包含一个包含所有排定通知的数组,但我认为有一些我不理解的地方,因为我得到了以下错误。

无法将类型为'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 ?? []
}

任何提示或指针都将被感激。

swift push-notification closures uilocalnotification completionhandler
1个回答
1
投票

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



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
}
© www.soinside.com 2019 - 2024. All rights reserved.