【发布时间】:2016-07-28 00:13:31
【问题描述】:
我在 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
}
有人有想法吗? 提前谢谢你
【问题讨论】:
标签: ios swift notifications localnotification