Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check user settings for push notification in Swift

Tags:

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 way :

let notificationType = UIApplication.sharedApplication().currentUserNotificationSettings()!.types
if notificationType == UIUserNotificationType.None {
    print("OFF")
} else {
    print("ON")
}

If push notifications are disabled by the user, is there any way to activate this from my app?

Or is there any alternative to send user to the push notification settings (Settings - Notifications - AppName)?

like image 409
Stack108 Avatar asked Mar 09 '16 10:03

Stack108


People also ask

Where do I find push notifications in Settings?

Turn on notifications for Android devicesTap More on the bottom navigation bar and select Settings. Tap Turn on notifications. Tap Notifications. Tap Show notifications.

How do I enable push notifications in provisioning profiles?

If "Push Notifications" are part of the Enabled Capabilities for that profile, then you can send Push Notifications to your users. If Push Notifications does not appear, then you will need to create a new distribution certificate and provisioning profile, upload it to the mag+ Publish portal, and rebuild your app.


2 Answers

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)!)
    }
}

Updated for iOS 10+ & Swift 5+

extension UIApplication {
    @objc class func openAppSettings() {
        shared.open(URL(string: openSettingsURLString)!,
                    options: [:],
                    completionHandler: nil)
    }
}
like image 189
salabaha Avatar answered Oct 19 '22 13:10

salabaha


For iOS 10 or higher

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

like image 21
Scooter Avatar answered Oct 19 '22 12:10

Scooter