等待完成处理程序完成

编程入门 行业动态 更新时间:2024-10-28 12:28:45
本文介绍了等待完成处理程序完成-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) } }

更多推荐

等待完成处理程序完成

本文发布于:2023-11-26 05:34:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!