swift - 如何在 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 语法如何以这种方式工作的资源,任何参考资料都会非常有帮助。
解决方案
的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)
推荐阅读
- javascript - 控制台在获取 404 响应时记录错误
- php - 如果值在 mysqli 数据库上,则不要在 php 上创建按钮
- c# - 计划的日常工作(使用简单的每日计划)与 QUARTZ 没有按预期触发?
- javascript - Javascript:知道调用了哪个对象函数
- excel - 为什么excel中的TEXTJOIN函数不能正常工作?
- ruby-on-rails - ActiveRecord 无法识别belongs_to 关联
- angular - 如何在量角器中忽略 websocket(在网络选项卡中找到)?
- c++ - 如何使用 Mako SDK 在 PDF 中模拟叠印?
- html - Bootstrap Navbar 和 Carousel 没有响应
- nginx - 本地ip或域名的AB负载测试?