我正在尝试检查用户通知是否已启用,如果没有启用,则希望弹出警报。因此,我有一个名为checkAvailability
的函数,它检查多个内容,包括用户通知授权状态。
func checkAvailabilty() -> Bool {
//
// other checking
//
var isNotificationsEnabled = false
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (granted, error) in
if granted {
isNotificationsEnabled = true
}
else {
isNotificationsEnabled = false
}
})
}
if isNotificationsEnabled {
return true
}
else {
// Throw alert: Remind user to activate notifications
return false
}
}
但完成处理程序被调用得太晚了。函数已经返回 false
,之后闭包中的代码才执行。
我尝试将整个语句 UNUserNotificationCenter.current().requestAuthorization()
放入同步调度队列中,但这并没有起作用。
另一种方法是从闭包内部返回,但我不知道如何实现。
checkAvailabilty()
中将完成处理程序作为参数添加,并在requestAuthorization的完成处理程序结束时调用它。 - shallowThought