I could not find some help for my problem here on SO or somewhere else, so I hope somebody of you guys can help me.
I'm trying to implement the functionality of a reminder in my iOS app, that the user enables by himself. The reminder is a local notification.
I'm not asking the user for permission for local notifications until he enables the reminder. After that I have to check, if the user granted the permissions and schedule a notification if so.
The core problem here is that the code doesn't stop executing on the ´registerUserNotificationSettings´ method and wait for the result of the upcoming UIAlertController. Therefore I cannot check for permissions directly after calling the method. I also don't want to ask for permission at the first start of the app because the user doesn't know why my app should send notifications and I think that this would be too much for the first start and for an optional feature.
I know of the appdelegate message ´didRegisterUserNotificationSettings´, which is sent after the question was answered. An idea is to firstly store the notification in a global variable and schedule it if the permission was granted. But that would be too much code that will be executed if the notification isn't even scheduled at the end.
So I'm looking for some solution to ask the user for permission and then decide whether to create and schedule the notification or not.
This is my problematic piece of code in the ´value changed´-event of a UISwitch, which does not work as intended:
//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
}
Does anyone has an idea? Thank you in advance