等待完成处理程序完成-Swift [英] Wait for completion handler to finish - Swift
问题描述
我正在尝试检查是否启用了UserNotifications,如果没有启用,我想发出警报。因此,我有一个 checkAvailability
函数,用于检查多项内容,包括UserNotification授权状态。
I am trying to check if UserNotifications are enabled and if not I want to throw an alert. So I have a function checkAvailability
which checks multiple things, including the UserNotification authorization status.
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
,然后执行清单中的代码。
But the completion handler gets called too late. The function already returned false
and after that the code in the colsure executes.
我试图放入整个语句 UNUserNotificationCenter.current()。requestAuthorization()
在同步分派队列中,但这不起作用。
I tried to put the whole statement UNUserNotificationCenter.current().requestAuthorization()
in a synchronous dispatch queue but this didn't work.
另一个方法是从闭包内部返回,但我不知道如何完成该操作。
Another approach would be to return from inside the closure but I have no idea how to accomplish that.
推荐答案
不要等待,为了方便使用枚举,请使用完成处理程序:
Do not wait, use a completion handler, for convenience with an enum:
enum AuthResult {
case success(Bool), failure(Error)
}
func checkAvailabilty(completion: @escaping (AuthResult) -> ()) {
//
// other checking
//
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (granted, error) in
if error != nil {
completion(.failure(error!))
} else {
completion(.success(granted))
}
})
}
并命名为:
checkAvailabilty { result in
switch result {
case .success(let granted) :
if granted {
print("access is granted")
} else {
print("access is denied")
}
case .failure(let error): print(error)
}
}
这篇关于等待完成处理程序完成-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!