0

The result of the test is always 0, as the code after the getNotificationSettingsWithCompletionHandler: block is executed before notificationsAlertAuthorization value is set in the block.

How do I solve this problem?

in AppDelegate.h:

- (BOOL)testNotificationsAuthorization;

in AppDelegate.m:

- (BOOL)testNotificationsAuthorization {
__block BOOL notificationsAlertAuthorization = 0;

[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    if (settings.alertSetting == UNNotificationSettingEnabled) {
        notificationsAlertAuthorization = YES;
        NSLog(@"settings.alertSetting: YES");
    }
}];

// gets executed before notificationsAlertAuthorization is set,
// result is always NO.
if (notificationsAlertAuthorization == YES) {
    NSLog(@"Alert Authorization Granted");
    return YES;
} else {
    NSLog(@"Alert Authorization NOT Granted");
    return NO;
} }

in ViewController:

- (IBAction)testForNotificationSettings:(UIButton *)sender {
BOOL result = [[[UIApplication sharedApplication] delegate] testNotificationsAuthorization];
NSLog(@"testForNotificationSettings result: %d", result);}

log:

2016-11-20 17:18:51.221 UserNotificationsTest[11873:536763] Alert Authorization NOT Granted 2016-11-20 17:18:51.222 UserNotificationsTest[11873:536763] testForNotificationSettings result: 0 2016-11-20 17:18:51.223 UserNotificationsTest[11873:536812] settings.alertSetting: YES

KaasCoder
  • 251
  • 5
  • 14

1 Answers1

3

You need to use CompletionHandlers in order to get the result, as you are getting the status for Notification in CompletionHandle and before getting the result you are comparing it, thats why you are getting wrong result.

Change your method like this

-(void) testNotificationsAuthorization :(void (^)(BOOL isActive))handler {
    [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        if (settings.alertSetting == UNNotificationSettingEnabled) {
            handler(YES);
            NSLog(@"settings.alertSetting: YES");
        } else {
            NSLog(@"settings.alertSetting: NO");
            handler(NO);
        }
    }];
}

and use it like this

[[[UIApplication sharedApplication] delegate] isNotificationActive:^(BOOL isActive) {
        if (isActive) {
            NSLog(@"settings.alertSetting: YES");
        } else {
            NSLog(@"settings.alertSetting: NO");
        }
    }];
Rajat
  • 10,977
  • 3
  • 38
  • 55