I am using local notifications in my app, before presenting user with new notification screen I want to check the authorisation status first. I am using shouldPerformSegue(identifier:, sender:) -> Bool method, so that if the notifications are not authorised by user, the scene where the user configures and saves a new notification is not presented:
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "AddReminder" {
// Check to see if notifications are authorised for this app by the user
let isAuthorised = NotificationsManager.checkAuthorization()
if isAuthorised {
print(isAuthorised)
return true
}
else {
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
(action: UIAlertAction) in
}
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsURL) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: { (success) in
print("Settings opened: \(success)")
})
}
}
alert.addAction(cancelAction)
alert.addAction(settingsAction)
present(alert, animated: true, completion: nil)
print(isAuthorised)
return false
}
}
// By default, transition
return true
}
Here is the method I use for authorisation check:
static func checkAuthorization() -> Bool {
// var isAuthorised: Bool
var isAuthorised = true
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }
})
print("Reached .notDetermined stage")
case .authorized:
isAuthorised = true
case .denied:
isAuthorised = false
}
}
//print("Last statement reached before the check itself")
return isAuthorised
}
I figured that the last statement in the above function (return isAuthorized) returned before the body of UNUserNotificationCenter.current().getNotificationSettings{} is executed, therefore it always returns whatever isAuthorized is configured to, at the very beginning of the method.
Question: Could you please suggest how I could check for authorisation using I better way, since my way does not even work.
This is only my first IOS app, so I am relatively new to IOS development; any help would be greatly appreciated.
If anyone having similar problem, then instead of using getNotificationsSettings(){} method, which will be computed after the enclosing method is returned; we could use different approach, i.e. getting currentUserNotificationSettings, which is notification settings of our app. Then check if current settings contain .aler, .sound and etc. If the answer is YES, then we could be sure that the applications has its notifications enabled.