Swift ios check if remote push notifications are enabled in ios9 and ios10
How can I check if the user has enabled remote notifications on ios 9 or ios 10?
If the user has not allowed or clicked No I want to toggle a message asking if they want to enable notifications.
Apple recommends to use UserNotifications
framework instead of shared instances. So, do not forget to import UserNotifications
framework. As this framework is new in iOS 10 it's really only safe to use this code in apps building for iOS10+
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { (settings) in
if settings.authorizationStatus == .notDetermined {
// Notification permission has not been asked yet, go for it!
} else if settings.authorizationStatus == .denied {
// Notification permission was previously denied, go to settings & privacy to re-enable
} else if settings.authorizationStatus == .authorized {
// Notification permission was already granted
}
})
You may check official documentation for further information: https://developer.apple.com/documentation/usernotifications
Updated answer after iOS 10 is using UNUserNotificationCenter
.
First you need to import UserNotifications
then
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { permission in
switch permission.authorizationStatus {
case .authorized:
print("User granted permission for notification")
case .denied:
print("User denied notification permission")
case .notDetermined:
print("Notification permission haven't been asked yet")
case .provisional:
// @available(iOS 12.0, *)
print("The application is authorized to post non-interruptive user notifications.")
case .ephemeral:
// @available(iOS 14.0, *)
print("The application is temporarily authorized to post notifications. Only available to app clips.")
@unknown default:
print("Unknow Status")
}
})
this code will work till iOS 9, for iOS 10 use the above code snippet.
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
// User is registered for notification
} else {
// Show alert user is not registered for notification
}
I tried Rajat's solution, but it didn't work for me on iOS 10 (Swift 3). It always said that push notifications were enabled. Below is how I solved the problem. This says "not enabled" if the user has tapped "Don't Allow" or if you have not asked the user yet.
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == [] {
print("notifications are NOT enabled")
} else {
print("notifications are enabled")
}
PS: The method currentUserNotificationSettings
was deprecated in iOS 10.0 but it's still working.