iOS 8-iOS13如何精准的判断通知权限是否打开

先说问题吧

在iOS13 系统上发现 不管是用户拒绝还是允许 granted 都是NO 所以打开通知判断不能用 requestAuthorizationWithOptions 回调方法来判断

[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:entity.types completionHandler:^(BOOL granted, NSError * _Nullable error) {
            [self trackUserGranted:granted];
 }];

因为在iOS 10 以及 iOS11 上异步线程调用 会造成主线程卡死

[[UIApplication sharedApplication] currentUserNotificationSettings == UIUserNotificationTypeNone

因此采用信号量来判断发现有一个缺点在异步线程调用的时候还是会crash

- (BOOL)userIsAllowPush {
    __block BOOL isAllow = NO;
    NSLog(@"1----%@",[NSThread currentThread]);

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
            NSLog(@"2----%@",[NSThread currentThread]); //判断为异步线程
            isAllow = (settings.authorizationStatus == UNAuthorizationStatusAuthorized);
            dispatch_semaphore_signal(semaphore);
        }];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
            isAllow = (settings.types != UIUserNotificationTypeNone);
            dispatch_semaphore_signal(semaphore);
        });
    }
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return isAllow;
}

因此决定采用block 方式来判断 在方法里面放到主线程里面

- (void)userIsAllowPush:(void (^)(BOOL))isOpenPushBlock {
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
          dispatch_async(dispatch_get_main_queue(), ^{
                        isAllow = (settings.authorizationStatus == UNAuthorizationStatusAuthorized);
                        isOpenPushBlock(isAllow);
            }];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
             UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
                   BOOL isAllow = (settings.types != UIUserNotificationTypeNone);
                   isOpenPushBlock(isAllow);
        });
    }
    
}

你可能感兴趣的:(iOS 8-iOS13如何精准的判断通知权限是否打开)