【发布时间】:2017-02-15 16:52:01
【问题描述】:
我正在尝试检查是否启用了 UserNotifications,如果没有,我想发出警报。所以我有一个函数checkAvailability 可以检查多项内容,包括 UserNotification 授权状态。
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,然后执行colsure中的代码。
我尝试将整个语句 UNUserNotificationCenter.current().requestAuthorization() 放入同步调度队列中,但这不起作用。
另一种方法是从闭包内部返回,但我不知道如何实现。
【问题讨论】:
-
将完成处理程序作为参数添加到
checkAvailabilty()并在requestAuthorization 的完成处理程序结束时调用它。
标签: ios swift closures grand-central-dispatch completionhandler