In my application I have in app settings for enabling/disabling push notifications. I ran into a case in which if user Don't allow notifications when the application launches and then enables it with Settings in the Application then authorization status is always Denied.
Here is my code for push notification in app delegate.
I have called registerForPushNotifications method in didFinishLaunching.
// MARK: Register app for push notificaitons
func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] granted, error in
printLogs("Permission granted: \(granted)")
// guard granted else { return }
if error == nil {
self?.getNotificationSettings()
}
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
printLogs("Notification settings: \(settings)")
switch settings.authorizationStatus {
case .authorized:
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
case .denied:
printLogs("Notifications Denied")
case .notDetermined:
printLogs("Notifications not determined")
default:
break
}
}
}
and for enabling notifications from settings I am using this code
AppDelegate.shared.registerForRemoteNotifications()
Once a user has denied the permissions for push notifications, he has to enable them from within the settings app in order to get push notifications. So on your settings screen, when user taps on enable notification option just take him to the notifications settings screen of your app. And from there he can enable it. Use this piece of code for opening settings app.
if let bundle = Bundle.main.bundleIdentifier,
let settings = URL(string: UIApplication.openSettingsURLString + bundle) {
if UIApplication.shared.canOpenURL(settings) {
UIApplication.shared.open(settings)
}
}
After enabling from within the settings app, status won't be denied
anymore.