测试结果始终为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;
} }
ViewController中的:
- (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:YES
答案 0 :(得分:3)
你需要使用CompletionHandlers
来获得结果,因为你在CompletionHandle中获得了Notification的状态,并且在得到你正在比较它的结果之前,这就是为什么你得到错误的结果。
像这样改变你的方法
-(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);
}
}];
}
并像这样使用
[[[UIApplication sharedApplication] delegate] isNotificationActive:^(BOOL isActive) {
if (isActive) {
NSLog(@"settings.alertSetting: YES");
} else {
NSLog(@"settings.alertSetting: NO");
}
}];