首页 > 解决方案 > 如何在 iOS 中获取用户的本地通知设置?

问题描述

我正在尝试创建一个返回布尔值的方法,以判断用户是否拥有授权通知。目前我有这个:

func notificationsAllowed() -> Bool{
            var valToRet = false
            UNUserNotificationCenter.current().getNotificationSettings() { settings in
                valToRet = (settings.authorizationStatus == .authorized)
                print(settings.authorizationStatus == .authorized)
            }
            return valToRet
        }

我不太了解“设置”的作用。此方法不起作用,因为 valToRet 从未更新。我的目标是制作一种方法来获取这些信息,但我发现这实际上表明了我对 swift 语言的理解存在一些重大漏洞,所以我想了解实际发生的情况。我很难找到有关 Swift 语法如何以这种方式工作的资源,任何参考资料都会非常有帮助。

标签: swiftswiftui

解决方案


getNotificationSettings函数UNUserNotificationCenter是异步的,并且有一个完成处理程序作为其唯一参数。

函数签名是:func getNotificationSettings(completionHandler: @escaping (UNNotificationSettings) -> Void)

这意味着与您的代码中相同的调用可以写成:

UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) -> Void in
    valToRet = (settings.authorizationStatus == .authorized)
    print(settings.authorizationStatus == .authorized)
})

这意味着您的函数在触发其回调notificationsAllowed()之前返回getNotificationSettings(),因此valToRet始终为假。

因此,你的函数notificationsAllowed()是多余的,你应该UNUserNotificationCenter.current().getNotificationSettings()在它的位置使用,等待完成处理程序关闭。我希望您必须重新构造调用此代码的位置,因为我认为您已经假设该值立即可用。

如果您调用它viewDidAppear(不推荐,一旦用户操作需要身份验证,您应该始终请求授权 - 例如他们可以单击“订阅”按钮),代码可能是:

func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings) -> Void in
        if settings.authorizationStatus == .notDetermined {
            // Display dialog advertising benefits of push notifications
            // Encourage user to allow, then present auth prompt
            // ...
        }
    })
}

额外的

我不太了解“设置”的作用。

在 Swift 中,in关键字用于声明闭包(匿名函数)的开始。对于标准函数,我们有func,尽管我们必须使用闭包(匿名函数)in来声明。

将其视为“获取参数settings并使用它in这一位丢弃代码”。

因此,之前的完成处理程序getNotificationSettings理论上可以编写为标准函数,而不是匿名闭包,例如:

func myNotificationSettingsCompletionHandler(settings: UNNotificationSettings) -> Void {
    if settings.authorizationStatus == .notDetermined {
        // Display dialog advertising benefits of push notifications
        // Encourage user to allow, then present auth prompt
        // ...
    }
}

completionHandler:然后我们可以在类似的参数中使用该函数getNotificationSettings

UNUserNotificationCenter.current().getNotificationSettings(completionHandler: myNotificationSettingsCompletionHandler)

推荐阅读