ios - 测试 UNNotificationSettings

标签 ios unnotificationrequest

测试结果始终为 0,因为 getNotificationSettingsWithCompletionHandler: block 之后的代码在 block 中设置 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;
} }

在 View Controller 中:

- (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

最佳答案

您需要使用 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");
        }
    }];

关于ios - 测试 UNNotificationSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40707028/

相关文章:

ios - 为什么我应该在 main 中为串行队列创建上下文并在 start 中为并发队列创建上下文?

ios - 我在哪里可以将.p12文件或“推送”通知 key 上传到Parse Server?

ios - Objective-C:使用 UNUserNotificationCenter 设置计时器以显示提醒

ios - 如何在 iOS 10 UserNotifications 上设置 NSCalendarUnitMinute repeatInterval?

ios - Swift UNUserNotification 不触发声音

ios - UICollectionView 方向改变事故?

android - 如何按使用量收取应用程序费用

ios - 派生 MKAnnotationView 并将其链接到 NIB 文件

ios - 特定日期和时间的本地通知不起作用。 swift

ios - 在 NSMutablearray 中添加新实例时发生奇怪的崩溃