Reputation: 305
I'm developing an app and need to push notification. I have to check whether user has allow notifications before pushing, so I write some code like this:
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionSound; //most snippets on the internet use 'UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;'
[center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
completion(granted);
}];
And I go to the system settings, enter the setting for the app, allow notification but open icon badge only. Here I still get granted
YES!
Why is that? I know most people write
UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
I just confused about how requestAuthorizationWithOptions:
works. There is nothing to do what kinds of notification options I open in app settings with options in code when granted
is YES?
Upvotes: 3
Views: 1487
Reputation: 305
Sorry, this "problem" results from another code snippet in our app project, which I didn't know until I asked my co-workers. Actually some code snippet in our project is in charge of request for notification authorization on first launch (when a system alert will pop). That code request for badge, alert and sound. So my code here wouldn't work any more. Thanks for @Boudhayan's and @zacks's answers!
Upvotes: 0
Reputation: 84
this method is to request the authorization.If you want to check whether the user has allow notifications,you should use [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler].it will give you a para named setting,you can use this to check.
Upvotes: 0
Reputation: 760
If your push notification interact with user, then you must call requestAuthorizationWithOptions:
this method to request authorization for the options you wanted.
Most people write UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
because they want the ability to update the application badge, present alert and play sound.
You are passing UNAuthorizationOptions options = UNAuthorizationOptionSound;
, this means for push notification, you only want to play sound.
When your app launches for the first time and calls the method, this means your app is asking for authorization for those options from user. User may grant or deny the authorization request, if user granted the then you completionHandler
called and granted
is set as YES
, otherwise it is NO
.
The system stores the user response so that app will not ask the user again for granting authorization request.
Upvotes: 1