iOS10及以上版本的通知授权方式

UNUserNotificationCenter *userNotificationCenter = [UNUserNotificationCenter currentNotificationCenter];
        userNotificationCenter.delegate = self;
//获取通知设置信息
        [userNotificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {

            //用户还未做出选择
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {

                //弹出授权框
                [userNotificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert + UNAuthorizationOptionBadge + UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {

                    if (granted) {

                    }else{
                        //首次授权为未授权状态,之后为已授权状态
                        DLog(@"没有开启通知");
                    }
                }];
            }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){

                //用户不同意授权时,弹出提示(最好只弹一次)
                UIAlertController *noticeNotificationAlertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"建议您开启通知功能,以便及时获取相关信息" preferredStyle:UIAlertControllerStyleAlert];
                [noticeNotificationAlertController addAction:[UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                }]];

                [noticeNotificationAlertController addAction:[UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

                    NSURL *appSettingsUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:appSettingsUrl]) {
                        [[UIApplication sharedApplication] openURL:appSettingsUrl];
                    }
                }]];

                [self.window.rootViewController presentViewController:noticeNotificationAlertController animated:YES completion:NULL];
            }else{

                //已授权
                DLog(@"已授权通知");
            }
        }];

猜你喜欢

转载自blog.csdn.net/heartofthesea/article/details/78204367
今日推荐