[ACCEPTED]-Determine on iPhone if user has enabled push notifications-push

Accepted answer
Score: 301

Call enabledRemoteNotificationsTypes and check the mask.

For example:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone) 
   // blah blah blah

iOS8 1 and above:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]
Score: 101

quantumpotato's issue:

Where types is given by

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];

one 7 can use

if (types & UIRemoteNotificationTypeAlert)

instead of

if (types == UIRemoteNotificationTypeNone) 

will allow you to check 6 only whether notifications are enabled (and 5 don't worry about sounds, badges, notification 4 center, etc.). The first line of code (types & UIRemoteNotificationTypeAlert) will 3 return YES if "Alert Style" is set to "Banners" or 2 "Alerts", and NO if "Alert Style" is set to 1 "None", irrespective of other settings.

Score: 54

In the latest version of iOS this method 2 is now deprecated. To support both iOS 7 1 and iOS 8 use:

UIApplication *application = [UIApplication sharedApplication];

BOOL enabled;

// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
    enabled = [application isRegisteredForRemoteNotifications];
}
else
{
    UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
    enabled = types & UIRemoteNotificationTypeAlert;
}
Score: 54

Updated code for swift4.0 , iOS11

import UserNotifications

UNUserNotificationCenter.current().getNotificationSettings { (settings) in
   print("Notification settings: \(settings)")
   guard settings.authorizationStatus == .authorized else { return }

   //Not authorised 
   UIApplication.shared.registerForRemoteNotifications()
}

Code for swift3.0 , iOS10

    let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
    if isRegisteredForRemoteNotifications {
        // User is registered for notification
    } else {
        // Show alert user is not registered for notification
    }

From iOS9 , swift 2.0 UIRemoteNotificationType 2 is deprecated, use following code

let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
if notificationType == UIUserNotificationType.none {
        // Push notifications are disabled in setting by user.
    }else{
  // Push notifications are enabled in setting by user.

}

simply 1 check whether Push notifications are enabled

    if notificationType == UIUserNotificationType.badge {
        // the application may badge its icon upon a notification being received
    }
    if notificationType == UIUserNotificationType.sound {
        // the application may play a sound upon a notification being received

    }
    if notificationType == UIUserNotificationType.alert {
        // the application may display an alert upon a notification being received
    }
Score: 33

Below you'll find a complete example that 4 covers both iOS8 and iOS7 (and lower versions). Please 3 note that prior to iOS8 you can't distinguish 2 between "remote notifications disabled" and 1 "only View in lockscreen enabled".

BOOL remoteNotificationsEnabled = false, noneEnabled,alertsEnabled, badgesEnabled, soundsEnabled;

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    // iOS8+
    remoteNotificationsEnabled = [UIApplication sharedApplication].isRegisteredForRemoteNotifications;

    UIUserNotificationSettings *userNotificationSettings = [UIApplication sharedApplication].currentUserNotificationSettings;

    noneEnabled = userNotificationSettings.types == UIUserNotificationTypeNone;
    alertsEnabled = userNotificationSettings.types & UIUserNotificationTypeAlert;
    badgesEnabled = userNotificationSettings.types & UIUserNotificationTypeBadge;
    soundsEnabled = userNotificationSettings.types & UIUserNotificationTypeSound;

} else {
    // iOS7 and below
    UIRemoteNotificationType enabledRemoteNotificationTypes = [UIApplication sharedApplication].enabledRemoteNotificationTypes;

    noneEnabled = enabledRemoteNotificationTypes == UIRemoteNotificationTypeNone;
    alertsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeAlert;
    badgesEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeBadge;
    soundsEnabled = enabledRemoteNotificationTypes & UIRemoteNotificationTypeSound;
}

if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    NSLog(@"Remote notifications enabled: %@", remoteNotificationsEnabled ? @"YES" : @"NO");
}

NSLog(@"Notification type status:");
NSLog(@"  None: %@", noneEnabled ? @"enabled" : @"disabled");
NSLog(@"  Alerts: %@", alertsEnabled ? @"enabled" : @"disabled");
NSLog(@"  Badges: %@", badgesEnabled ? @"enabled" : @"disabled");
NSLog(@"  Sounds: %@", soundsEnabled ? @"enabled" : @"disabled");
Score: 25

Swift 3+

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            // settings.authorizationStatus == .authorized
        })
    } else {
        return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
    }

RxSwift Observable Version for iOS10+:

import UserNotifications
extension UNUserNotificationCenter {
    static var isAuthorized: Observable<Bool> {
        return Observable.create { observer in
            DispatchQueue.main.async {
                current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
                    if settings.authorizationStatus == .authorized {
                        observer.onNext(true)
                        observer.onCompleted()
                    } else {
                        current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
                            observer.onNext(granted)
                            observer.onCompleted()
                        }
                    }
                })
            }
            return Disposables.create()
        }
    }
}

0

Score: 17

In trying to support both iOS8 and lower, I 2 didn't have much luck using isRegisteredForRemoteNotifications as Kevin suggested. Instead 1 I used currentUserNotificationSettings, which worked great in my testing.

+ (BOOL)notificationServicesEnabled {
    BOOL isEnabled = NO;

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
        UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
            isEnabled = NO;
        } else {
            isEnabled = YES;
        }
    } else {
        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        if (types & UIRemoteNotificationTypeAlert) {
            isEnabled = YES;
        } else{
            isEnabled = NO;
        }
    }

    return isEnabled;
}
Score: 15

Unfortunately none of these solutions provided 44 really solve the problem because at the end of 43 the day the APIs are seriously lacking when 42 it comes to providing the pertinent information. You 41 can make a few guesses however using currentUserNotificationSettings (iOS8+) just 40 isn't sufficient in its current form to 39 really answer the question. Although a lot 38 of the solutions here seem to suggest that 37 either that or isRegisteredForRemoteNotifications is more of a definitive 36 answer it really is not.

Consider this:

with 35 isRegisteredForRemoteNotifications documentation states:

Returns YES if the 34 application is currently registered for 33 remote notifications, taking into account 32 any systemwide settings...

However if you 31 throw a simply NSLog into your app delegate to 30 observe the behavior it is clear this does 29 not behave the way we are anticipating it 28 will work. It actually pertains directly 27 to remote notifications having been activated 26 for this app/device. Once activated for 25 the first time this will always return YES. Even 24 turning them off in settings (notifications) will 23 still result in this returning YES this is 22 because, as of iOS8, an app may register 21 for remote notifications and even send to 20 a device without the user having notifications 19 enabled, they just may not do Alerts, Badges 18 and Sound without the user turning that 17 on. Silent notifications are a good example 16 of something you may continue to do even 15 with notifications turned off.

As far as 14 currentUserNotificationSettings it indicates one of four things:

Alerts 13 are on Badges are on Sound is on None are 12 on.

This gives you absolutely no indication 11 whatsoever about the other factors or the 10 Notification switch itself.

A user may in 9 fact turn off badges, sound and alerts but 8 still have show on lockscreen or in notification 7 center. This user should still be receiving 6 push notifications and be able to see them 5 both on the lock screen and in the notification 4 center. They have the notification switch 3 on. BUT currentUserNotificationSettings will return: UIUserNotificationTypeNone in that case. This 2 is not truly indicative of the users actual 1 settings.

A few guesses one can make:

  • if isRegisteredForRemoteNotifications is NO then you can assume that this device has never successfully registered for remote notifications.
  • after the first time of registering for remote notifications a callback to application:didRegisterUserNotificationSettings: is made containing user notification settings at this time since this is the first time a user has been registered the settings should indicate what the user selected in terms of the permission request. If the settings equate to anything other than: UIUserNotificationTypeNone then push permission was granted, otherwise it was declined. The reason for this is that from the moment you begin the remote registration process the user only has the ability to accept or decline, with the initial settings of an acceptance being the settings you setup during the registration process.
Score: 8

To complete the answer, it could work something 3 like this...

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
switch (types) {
   case UIRemoteNotificationTypeAlert:
   case UIRemoteNotificationTypeBadge:
       // For enabled code
       break;
   case UIRemoteNotificationTypeSound:
   case UIRemoteNotificationTypeNone:
   default:
       // For disabled code
       break;
}

edit: This is not right. since 2 these are bit-wise stuff, it wont work with 1 a switch, so I ended using this:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
UIRemoteNotificationType typesset = (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
if((types & typesset) == typesset)
{
    CeldaSwitch.chkSwitch.on = true;
}
else
{
    CeldaSwitch.chkSwitch.on = false;
}
Score: 5

For iOS7 and before you should indeed use 7 enabledRemoteNotificationTypes and check if it equals (or doesn't equal 6 depending on what you want) to UIRemoteNotificationTypeNone.

However 5 for iOS8 it is not always enough to only check 4 with isRegisteredForRemoteNotifications as many state above. You should also 3 check if application.currentUserNotificationSettings.types equals (or doesn't equal depending 2 on what you want) UIUserNotificationTypeNone!

isRegisteredForRemoteNotifications might return true even 1 though currentUserNotificationSettings.types returns UIUserNotificationTypeNone.

Score: 5

iOS8+ (OBJECTIVE C)

#import <UserNotifications/UserNotifications.h>


[[UNUserNotificationCenter currentNotificationCenter]getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {

    switch (settings.authorizationStatus) {
          case UNAuthorizationStatusNotDetermined:{

            break;
        }
        case UNAuthorizationStatusDenied:{

            break;
        }
        case UNAuthorizationStatusAuthorized:{

            break;
        }
        default:
            break;
    }
}];

0

Score: 4
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
    // blah blah blah
{
    NSLog(@"Notification Enabled");
}
else
{
    NSLog(@"Notification not enabled");
}

Here we get the UIRemoteNotificationType 4 from UIApplication. It represents the state 3 of push notification of this app in the 2 setting, than you can check on its type 1 easily

Score: 4

I try to support iOS 10 and above using 9 solution provide by @Shaheen Ghiassy but 8 find deprivation issue enabledRemoteNotificationTypes. So, the solution 7 I find by using isRegisteredForRemoteNotifications instead of enabledRemoteNotificationTypes which deprecated 6 in iOS 8. Below is my updated solution that 5 worked perfectly for me:

- (BOOL)notificationServicesEnabled {
    BOOL isEnabled = NO;
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
        UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
            isEnabled = NO;
        } else {
            isEnabled = YES;
        }
    } else {

        if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
            isEnabled = YES;
        } else{
            isEnabled = NO;
        }
    }
    return isEnabled;
}

And we can call 4 this function easily and be accessing its 3 Bool value and can convert it into the string 2 value by this:

NSString *str = [self notificationServicesEnabled] ? @"YES" : @"NO";

Hope it will help others too 1 :) Happy coding.

Score: 3

Though Zac's answer was perfectly correct 3 till iOS 7, it has changed since iOS 8 arrived. Because 2 enabledRemoteNotificationTypes has been deprecated from iOS 8 onwards. For 1 iOS 8 and later, you need to use isRegisteredForRemoteNotifications.

  • for iOS 7 and before --> Use enabledRemoteNotificationTypes
  • for iOS 8 and later --> Use isRegisteredForRemoteNotifications.
Score: 2

This Swifty solution worked well for me (iOS8+),

Method:

func isNotificationEnabled(completion:@escaping (_ enabled:Bool)->()){
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            let status =  (settings.authorizationStatus == .authorized)
            completion(status)
        })
    } else {
        if let status = UIApplication.shared.currentUserNotificationSettings?.types{
            let status = status.rawValue != UIUserNotificationType(rawValue: 0).rawValue
            completion(status)
        }else{
            completion(false)
        }
    }
}

Usage:

isNotificationEnabled { (isEnabled) in
            if isEnabled{
                print("Push notification enabled")
            }else{
                print("Push notification not enabled")
            }
        }

Ref

0

Score: 0

re:

this is correct

if (types & UIRemoteNotificationTypeAlert)

but following is correct 2 too ! (as UIRemoteNotificationTypeNone 1 is 0 )

if (types == UIRemoteNotificationTypeNone) 

see the following

NSLog(@"log:%d",0 & 0); ///false
NSLog(@"log:%d",1 & 1); ///true
NSLog(@"log:%d",1<<1 & 1<<1); ///true
NSLog(@"log:%d",1<<2 & 1<<2); ///true
NSLog(@"log:%d",(0 & 0) && YES); ///false
NSLog(@"log:%d",(1 & 1) && YES); ///true
NSLog(@"log:%d",(1<<1 & 1<<1) && YES); ///true
NSLog(@"log:%d",(1<<2 & 1<<2) && YES); ///true
Score: 0

Here's how to do this in Xamarin.ios.

public class NotificationUtils
{
    public static bool AreNotificationsEnabled ()
    {
        var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings;
        var types = settings.Types;
        return types != UIUserNotificationType.None;
    }
}

If 2 you are supporting iOS 10+ only go with 1 the UNUserNotificationCenter method.

Score: 0

In Xamarin, all above solution does not 3 work for me. This is what I use instead:

public static bool IsRemoteNotificationsEnabled() {
    return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}

It's 2 getting a live update also after you've 1 changed the notification status in Settings.

More Related questions