测试的结果始终为 0,因为 getNotificationSettingsWithCompletionHandler: 块之后的代码在该块中设置 notificationsAlertAuthorization 值之前执行。
我该如何解决这个问题?
在 AppDelegate.h 中:
- (BOOL)testNotificationsAuthorization;
在 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;
} }
在视图控制器中:
- (IBAction)testForNotificationSettings:(UIButton *)sender {
BOOL result = [[[UIApplication sharedApplication] delegate] testNotificationsAuthorization];
NSLog(@"testForNotificationSettings result: %d", result);}
日志:
2016-11-20 17:18:51.221 UserNotificationsTest[11873:536763] 未授予警报授权 2016-11-20 17:18:51.222 UserNotificationsTest[11873:536763] testForNotificationSettings 结果:0 2016-11-20 17:18:51.223 UserNotificationsTest[11873:536812] settings.alertSetting: 是