Determine on iPhone if user has enabled push notifications
Asked Answered
D

19

211

I'm looking for a way to determine if the user has, via settings, enabled or disabled their push notifications for my application.

Dystrophy answered 8/10, 2009 at 3:5 Comment(0)
C
303

Call enabledRemoteNotificationsTypes and check the mask.

For example:

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

iOS8 and above:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]
Clovis answered 8/10, 2009 at 3:13 Comment(13)
iOS 5: This checks for what kind of push notifications the app uses regardless of weather the app is in your phone's notification center or not. I disabled push notifications for my app and still got types == 6. Upon disabling sound and alert style, I got types == UIRemoteNotificationTypeNone.Enthalpy
quantumpotato, set the display-style to none. then its TypeNone.Pera
As quantumpotato pointed out, this answer no longer handles all cases and isn't a complete solution.Ppm
I am always getting 7 irrespect notification service is ON or OFFDesmarais
What's going on with Apple? I wish I could hear their response on this issue. How can we develop great apps without knowing such basic info??Rockie
Zac's answer is wrong: UIRemoteNotificationType is a bitmask, so it should be checked with &, not ==!Devotional
@kpower. no.. comparison to UIRemoteNotificationTypeNone with == is fine because it's equal to zero.Clovis
@ZacBowling yep, my fault.Devotional
for iOS 8 check this if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) { UIRemoteNotificationType types = [[UIApplication sharedApplication] currentUserNotificationSettings]; }Tenenbaum
on iOS7 , enabledRemoteNotificationTypes always gives UIRemoteNotificationTypeNone , although I have selected Sound,Badge etc. How to identify if User has enabled/disabled Notification options.Flibbertigibbet
@ZacBowling - solution for iOS 8 and higher is wrong because it checks only if user registered for remote notification. According to the documentation: This method reflects only the successful completion of the remote registration process that begins when you call the registerForRemoteNotifications method. This method does not reflect whether remote notifications are actually available due to connectivity issues. The value returned by this method takes into account the user’s preferences for receiving remote notifications.Aarau
So in my opinion you should also check [[UIApplication sharedApplication] currentUserNotificationSettings];Aarau
isRegisteredForRemoteNotifications is not work when user close notifications from settings. let notificationSettings = UIApplication.shared.currentUserNotificationSettings?.types.rawValue if notificationSettings == 0 { // notification is closed }Ellora
B
101

quantumpotato's issue:

Where types is given by

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];

one can use

if (types & UIRemoteNotificationTypeAlert)

instead of

if (types == UIRemoteNotificationTypeNone) 

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

Bedstraw answered 27/3, 2012 at 22:28 Comment(5)
this does not address quantumpotato's issue. He is not concerned with just alerts but pointing out that you cannot discern through enabledRemoteNotifications whether the user has toggled the Notification Center setting on or off.Repercussion
My answer may not directly answer "how to determine if app is in Notification Center", but it does offer a way to check whether or not the user will receive notifications for your app, which I think is an answer in the spirit of the question. I don't think it is possible to check the former.Bedstraw
The trick of "if (types & UIRemoteNotificationTypeAlert)" is very good.Gritty
Make sure you understand why the trick works! Bitwise operators are very useful, and bitmasks are common in Cocoa. Check out https://mcmap.net/q/128755/-understanding-the-bitwise-and-operatorBedstraw
In Swift2/XCode7 the bitwise operation fails with the error Binary operator '&' cannot be applied to two 'UIUserNotificationType' operands. You can use contains instead grantedSettings.types.contains(notificationType)Demimonde
B
55

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 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 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
    }
Bellda answered 1/10, 2015 at 9:25 Comment(0)
H
54

In the latest version of iOS this method is now deprecated. To support both iOS 7 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;
}
Heliozoan answered 19/9, 2014 at 23:53 Comment(4)
What about local notifications ? iOS 8 now requires the user to allow them. But then how to check later that these were allowed or not ?Inkerman
@FredA. Check UserNotifications. I don't have a full answer now, unfortunately.Clarence
@FredA. Here is my take on the subject.Clarence
in Swift I cannot do enabled = types & UIRemoteNotificationTypeAlert. Error: types is not boolMama
I
33

Below you'll find a complete example that covers both iOS8 and iOS7 (and lower versions). Please note that prior to iOS8 you can't distinguish between "remote notifications disabled" and "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");
Issi answered 9/2, 2015 at 14:25 Comment(1)
userNotificationSettings.types & UIUserNotificationTypeNone will always be false, as UIUserNotificationTypeNone is an empty bit mask, it's the absence of the other bits. for None you just want to check equality.Brei
I
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()
        }
    }
}
Igneous answered 23/9, 2016 at 15:44 Comment(3)
you save my day. :)Syntax
Thanks i was searching this for an hour.Rumpf
getNotificationSettings(...) is asynchronous so the return inside will be ignoreSantalaceous
R
17

In trying to support both iOS8 and lower, I didn't have much luck using isRegisteredForRemoteNotifications as Kevin suggested. Instead 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;
}
Reflective answered 5/3, 2015 at 11:0 Comment(3)
This doesn't apply when the application is freshly installed. The method will always return NO, and the pop up permission for push notifications will never appear. Thus, on the device's settings, the app will not appear if you want to change the notification settings for that app (allow/disallow). Anyone has any idea how to work around this problem?Ratfink
Notification settings are persisted even when an app is deleted. So if you're app is fully brand new, then this method will work. If your app was deleted but then reinstalled, then the permissions are still in the system and Apple won't provide you the opportunity to re-ask for permissions.Reflective
I see some redundant code: isEnabled = NO; in your if cases is not needed as it has been initialised as NOCassilda
H
15

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

Consider this:

with isRegisteredForRemoteNotifications documentation states:

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

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

As far as currentUserNotificationSettings it indicates one of four things:

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

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

A user may in fact turn off badges, sound and alerts but still have show on lockscreen or in notification center. This user should still be receiving push notifications and be able to see them both on the lock screen and in the notification center. They have the notification switch on. BUT currentUserNotificationSettings will return: UIUserNotificationTypeNone in that case. This is not truly indicative of the users actual 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.
Henpeck answered 25/3, 2016 at 14:36 Comment(0)
E
8

To complete the answer, it could work something 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 these are bit-wise stuff, it wont work with 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;
}
Erikerika answered 21/2, 2013 at 17:27 Comment(1)
I considered (for my situation) sound notifications as not enabled (Since I require text to consider them enabled for my app functionality)Erikerika
P
6

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;
    }
}];
Productive answered 9/8, 2017 at 13:27 Comment(0)
P
5

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

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

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

Philander answered 4/2, 2015 at 14:17 Comment(0)
V
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 from UIApplication. It represents the state of push notification of this app in the setting, than you can check on its type easily

Verticillaster answered 22/4, 2014 at 15:11 Comment(1)
please explain what this code does, writing code does not simply answer the question.Condottiere
M
4

I try to support iOS 10 and above using solution provide by @Shaheen Ghiassy but find deprivation issue enabledRemoteNotificationTypes. So, the solution I find by using isRegisteredForRemoteNotifications instead of enabledRemoteNotificationTypes which deprecated in iOS 8. Below is my updated solution that 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 this function easily and be accessing its Bool value and can convert it into the string value by this:

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

Hope it will help others too :) Happy coding.

Mele answered 21/8, 2017 at 10:39 Comment(0)
S
3

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

  • for iOS 7 and before --> Use enabledRemoteNotificationTypes
  • for iOS 8 and later --> Use isRegisteredForRemoteNotifications.
Susceptible answered 15/12, 2014 at 15:1 Comment(0)
B
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

Brundage answered 21/7, 2017 at 10:0 Comment(0)
W
0

re:

this is correct

if (types & UIRemoteNotificationTypeAlert)

but following is correct too ! (as UIRemoteNotificationTypeNone 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
Woodnote answered 16/5, 2012 at 2:48 Comment(0)
P
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 you are supporting iOS 10+ only go with the UNUserNotificationCenter method.

Picrate answered 1/8, 2017 at 11:18 Comment(0)
B
0

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

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

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

Blasting answered 21/8, 2017 at 3:34 Comment(0)
T
-1

Full easy copy and paste code built from @ZacBowling's solution (https://mcmap.net/q/126040/-determine-on-iphone-if-user-has-enabled-push-notifications)

this will also bring the user to your app settings and allow them to enable immediately

I also added in a solution for checking if location services is enabled (and brings to settings as well)

// check if notification service is enabled
+ (void)checkNotificationServicesEnabled
{
    if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification Services Disabled!"
                                                            message:@"Yo don't mess around bro! Enabling your Notifications allows you to receive important updates"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        alertView.tag = 300;

        [alertView show];

        return;
    }
}

// check if location service is enabled (ref: https://mcmap.net/q/128756/-checking-location-service-permission-on-ios)
+ (void)checkLocationServicesEnabled
{
    //Checking authorization status
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
                                                            message:@"You need to enable your GPS location right now!!"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        //TODO if user has not given permission to device
        if (![CLLocationManager locationServicesEnabled])
        {
            alertView.tag = 100;
        }
        //TODO if user has not given permission to particular app
        else
        {
            alertView.tag = 200;
        }

        [alertView show];

        return;
    }
}

// handle bringing user to settings for each
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if(buttonIndex == 0)// Cancel button pressed
    {
        //TODO for cancel
    }
    else if(buttonIndex == 1)// Settings button pressed.
    {
        if (alertView.tag == 100)
        {
            //This will open ios devices location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
        }
        else if (alertView.tag == 200)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
        else if (alertView.tag == 300)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}

GLHF!

Toll answered 22/6, 2016 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.