I have push notifications in my app. Whenever the app is launched, I would like to check whether the user has enabled push notification for my application.
I do it this
This is the Swift 3 version where you can check whether notifications are enabled or disabled.
let notificationType = UIApplication.shared.currentUserNotificationSettings?.types
if notificationType?.rawValue == 0 {
print("Disabled")
} else {
print("Enabled")
}
There is no way to change settings from the app. But you can lead user to application specific system settings using this code.
extension UIApplication {
class func openAppSettings() {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
}
Updated for Swift 3.0
extension UIApplication {
class func openAppSettings() {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}
}
Checking if push notifications have been enabled for your app has changed dramatically for Swift 3. Use this instead of the above examples if you are using Swift 3.
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if(settings.authorizationStatus == .authorized)
{
print("Push authorized")
}
else
{
print("Push not authorized")
}
}
Here is Apple's documentation on how to further refine your check: https://developer.apple.com/reference/usernotifications/unnotificationsettings/1648391-authorizationstatus
Swift 4 version of salabaha's answer
extension UIApplication {
class func openAppSettings() {
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: {enabled in
// ... handle if enabled
})
}
Here is the most thorough way, as of iOS12 and Swift 5:
_ = UNUserNotificationCenter.current().getNotificationSettings { (settings) in
switch settings.authorizationStatus {
case .notDetermined:
<#code#>
case .denied:
<#code#>
case .authorized:
<#code#>
case .provisional:
<#code#>
@unknown default:
<#fatalError()#>
}
}
Short answer: No, if a user has denied your request for push notifications you cannot ask them again, you should point them to the settings page, you can do this with an alert informing them of the steps and two options "Ok" and "Go to settings", this is where you'd use Roman's code.
Long Answer: You should only ask the user for push notifications when you absolutely need to AND if you're going to ask it helps to preface with a little view explaining why you want/need to send push notifications, this is a great TechCrunch article that will help you get better retention/acceptance from your users - http://techcrunch.com/2014/04/04/the-right-way-to-ask-users-for-ios-permissions/