我在 SO 或其他地方找不到解决我的问题的帮助,所以我希望你们中的一些人可以帮助我。
我正在尝试在我的 iOS 应用程序中实现用户自己启用的提醒功能。该提醒是本地通知。
在用户启用提醒之前,我不会向用户请求本地通知的许可。之后我必须检查用户是否授予了权限并安排通知(如果是)。
这里的核心问题是代码不会停止在“registerUserNotificationSettings”方法上执行并等待即将到来的 UIAlertController 的结果。因此我无法在调用该方法后直接检查权限。 我也不想在应用程序第一次启动时请求许可,因为用户不知道为什么我的应用程序应该发送通知,并且我认为这对于第一次启动和可选功能来说太多了。
我知道 appdelegate 消息“didRegisterUserNotificationSettings”,该消息是在回答问题后发送的。一个想法是首先将通知存储在全局变量中,并在授予权限时安排它。但是,如果最后没有安排通知,那么将执行的代码太多。
因此,我正在寻找一些解决方案来请求用户许可,然后决定是否创建和安排通知。
这是我在 UISwitch 的“值更改”事件中出现问题的代码,它无法按预期工作:
//check if the app is allowed to send notifications or ask the user
var settingTypes = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
if (settingTypes?.contains(.Alert) == false) {
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
//get NotificationSettings again after the user was asked
settingTypes = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
}
//now check if if notifications are finally permitted
if (settingTypes?.contains(.Alert) == true) {
let notification = UILocalNotification()
* create notification *
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
else {
switchNotification.on = false
}
有人有想法吗? 预先感谢您
最佳答案
在 AppDelegate
中声明一个 Closure
var userNotificationChanged: ((settings: UIUserNotificationSettings) -> Void)?
并在用户注册通知
时调用闭包
您的 AppDelegate
didRegisterUserNotificationSettings
如下所示
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if (userNotificationChanged != nil) {
userNotificationChanged!(settings: notificationSettings)
}
}
现在,在 UISwitch
的 valueChanged
事件中设置 closure
并在其中执行所需的操作:
(UIApplication.sharedApplication().delegate as! AppDelegate).userNotificationChanged = { (settings: UIUserNotificationSettings) -> Void in
//Schedule your notification here
}
关于ios - 询问用户本地通知并随后执行任务 - Swift 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625165/