How to check if push notification is actually enabled in iOS

Issue #455

There are times we want to log if user can receive push notification. We may be tempted to merely use isRegisteredForRemoteNotifications but that is not enough. From a user ‘s point of view, they can either receive push notification or not. But behind the scene, many factors are in the game. It can be that user has disabled push notification in app settings or in iOS Settings. It can also be that user enables push notification but disables all sound or banner display mechanism.

isRegisteredForRemoteNotifications is that your app has connected to APNS and get device token, this can be for silent push notification
currentUserNotificationSettings is for user permissions, without this, there is no alert, banner or sound push notification delivered to the app
Here is the check

1
2
3
4
5
6
7
8
9
static var isPushNotificationEnabled: Bool {
guard let settings = UIApplication.shared.currentUserNotificationSettings
else {
return false
}

return UIApplication.shared.isRegisteredForRemoteNotifications
&& !settings.types.isEmpty
}

For iOS 10, with the introduction of UserNotifications framework, instead of checking for currentUserNotificationSettings, you should use UserNotifications framework

1
2
3
4
5
6
7
8
9
10
center.getNotificationSettings(completionHandler: { settings in
switch settings.authorizationStatus {
case .authorized, .provisional:
print("authorized")
case .denied:
print("denied")
case .notDetermined:
print("not determined, ask user for permission now")
}
})

Push notification can be delivered to our apps in many ways, and we can ask for that

1
2
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge])

User can go to Settings app and turn off any of those at any time, so it’s best to check for that in the settings object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding {


open var authorizationStatus: UNAuthorizationStatus { get }


open var soundSetting: UNNotificationSetting { get }

open var badgeSetting: UNNotificationSetting { get }

open var alertSetting: UNNotificationSetting { get }


open var notificationCenterSetting: UNNotificationSetting { get }
}

Original answer https://stackoverflow.com/a/44407710/1418457

Comments