I have a class that handles local notifications and I'd like to determine whether they are enabled or not based on whether any are scheduled. So I thought I could try creating a computed property that contains an array of all the notifications scheduled, but I think there's something I don't understand because I get the following error:
Cannot convert return expression of type 'Void' to return type '[UNNotificationRequest]'
var notifications: [UNNotificationRequest] {
center.getPendingNotificationRequests { notifications in return notifications }
}
Simply printing the notifications from within the completion handler works fine, so I am able to get them correctly, just not assign them to the variable.
I also tried creating a separate variable and returning that, but this always defaults to the empty default value I provided.
var notifications: [UNNotificationRequest] {
var retrievedNotifications: [UNNotificationRequest]?
center.getPendingNotificationRequests { notifications in retrievedNotifications = notifications }
return retrievedNotifications ?? []
}
Any tips or pointers would be appreciated.
You can probably use dispatch groups like as follows. What you are actually doing is waiting for all your notifications to be retrieved from a thread and then continue
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
}