美文网首页
iOS开发通知权限

iOS开发通知权限

作者: 铁头娃_e245 | 来源:发表于2021-07-11 18:33 被阅读0次

    iOS 10以后,苹果统一使用 UNUserNotifications ,以前的API都被标为弃用了。(如application:didReceiveRemoteNotification:)

    注册通知

    使用UNUserNotificationCenter需要引用头文件

    #ifdef NSFoundationVersionNumber_iOS_9_x_Max
    #import <UserNotifications/UserNotifications.h>
    #endif
    

    检查是否有push推送权限

    // 检查是否有push推送权限
    - (void)checkCurrentNotificationStatus{
        if (@available(iOS 10 , *)){
            [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined){
                    // 未选择
                }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                    // 没权限
                }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                    // 已授权
                    [self requestNotification];
                }
            }];
        }
        else if (@available(iOS 8 , *))
        {
            UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
            if (setting.types == UIUserNotificationTypeNone) {
                // 没权限
            }else{
                // 已授权
                [self requestNotification];
            }
        }
        else{
            UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
            if (type == UIUserNotificationTypeNone)
            {
                // 没权限
            }
        }
    }
    

    消息权限弹窗

    //消息权限弹窗
    - (void)showUserNotificationAlert {
        //弹窗提示,是否开通通知权限
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您需要开启系统通知权限,才可以正常接收消息,请到设置->通知中开启【XXX】消息通知。" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url];
                }
            });
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
    

    注册消息通知

    注意:iOS10以后的api UNUserNotificationCenter在request调用后就立马回调deviceToken的代理方法,不会等待点击结果,需要注意运行时序的问题,所以项目里加了一个通知方法,点击后再上传deviceToken

    //注册消息通知
    -(void)requestNotification
    {
        //ios 10的实现方法出现弹窗的时候就会回调didRegisterForRemoteNotificationsWithDeviceToken,不去等待异步结果
        if (@available(iOS 10, *))
        {
            UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
            [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    // 允许推送
                    NSLog(@"注册通知成功");
                    //点击确认后再次上传deviceToken
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"requestNotificationSuccess" object:nil];
                }else{
                    //不允许
                }
            }];
        }
        //ios 8的实现方法只有点击了同意或不同意按钮才回调didRegisterForRemoteNotificationsWithDeviceToken,等待结果后才回调
        else if(@available(iOS 8 , *))
        {
            UIApplication * application = [UIApplication sharedApplication];
            [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
        }
        else
        {
            UIApplication * application = [UIApplication sharedApplication];
            [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
        }
        
        // 注册获得device Token
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        });
    }
    

    系统通知的回调方法

    deviceToken(在注册成功后进行回调,每次启动都要注册一次registerForRemoteNotifications)

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
          //deviceToken
    }
    

    接收通知方法

    /*
     1.已弃用。iOS 3.0–10.0的版本,消息到达时被回调
     2.只有在程序处于运行状态(前台or后台)调用,但是你强制杀死程序之后,来了远程推送,系统不会自动进入你的程序,这个时候application:didReceiveRemoteNotification:就不会被调用。
     3.如果实现了application: didReceiveRemoteNotification: fetchCompletionHandler:则该方法不会被调用(如果没有实现就会调用这个,属于系统的兜底逻辑)
     */
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
        NSLog(@"%@",userInfo[@"url"]);
    }
    
    /*
     1.当程序launch完毕之后,就会调用(>iOS7版本)
     2.应用在前后台,kill掉的状态在收到推送都会触发该方法(应用kill时,用户点击push后,appFinishLaunch中会带着push消息,同时这个接口也会被调用)
     3.即收到消息就会触发,所以要判断前后台状态
     4.在ios10后如果设置代理UNUserNotificationCenterDelegate,并实现了willPresentNotification,应用在前台时该方法会变为只有点击时候才触发,收到推送的时候会触发willPresentNotification方法来控制显示效果,如果还实现了代理的点击方法didReceiveNotificationResponse,那么该方法不会触发。
     */
    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
        NSLog(@"%@",userInfo[@"url"]);
    }
    
    //本地推送触发方法
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
        NSLog(@"%@",notification.userInfo[@"url"]);
    }
    

    iOS10后新的api

    代理方法

    <UNUserNotificationCenterDelegate>
    

    设置代理

    注意:这个代理只能在application里设置 (这也是为什么有一些app设置了[UNUserNotificationCenter currentNotificationCenter].delegate代理没有触发代理方法的原因)

    // The delegate can only be set from an application
    // 官方解释,这个代理只能在application里设置
    // iOS10后通知前台显示需要设置该代理
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    

    设置代理后通知的显示方法

    如果没有实现这个回调,无论接收到通知和点击通知都会触发application:didReceiveRemoteNotification:fetchCompletionHandler:方法,但实现了willPresentNotification方法后,didReceiveRemoteNotification只负责点击事件,在前台接收到PUSH后由willPresentNotification处理

    #pragma mark UNUserNotificationCenterDelegate代理方法
    //当应用在前台时,收到通知会触发这个代理方法
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
        // 前台显示,需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置, 不设置alert当APP在前台时就没有提示
        completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    }
    

    点击推送消息后回调

    如果实现了这个回调,则ios10以后的机型上不会触发application:didReceiveRemoteNotification:fetchCompletionHandler:方法,只会触发下面代理方法,如果没设置代理代码,则去触发didReceiveRemoteNotification方法

    //点击推送消息后回调
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler{
        NSLog(@"Userinfo %@",response.notification.request.content.userInfo);
    }
    

    本地PUSH

    - (void)localNotification{
        if (@available(iOS 10.0, *)) {
            NSString *requestID = @"123hhhh";
            //第一步:获取推送通知中心
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge)
                                  completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (!error) {
                    NSLog(@"succeeded!");
                }
            }];
            center.delegate = self;
            
            //第二步:设置推送内容
            UNMutableNotificationContent *content = [UNMutableNotificationContent new];
            content.title = @"推送中心标题";
            content.subtitle = @"副标题";
            content.body  = @"这是UNUserNotificationCenter信息中心";
            content.badge = @20;
            content.categoryIdentifier = @"categoryIdentifier";
            
            UNNotificationAction *action = [UNNotificationAction actionWithIdentifier:@"enterApp"
                                                                                title:@"进入应用"
                                                                              options:UNNotificationActionOptionForeground];
            UNNotificationAction *clearAction = [UNNotificationAction actionWithIdentifier:@"destructive"
                                                                                     title:@"忽略2"
                                                                                   options:UNNotificationActionOptionDestructive];
            UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"categoryIdentifier"
                                                                                      actions:@[action,clearAction]
                                                                            intentIdentifiers:@[requestID]
                                                                                      options:UNNotificationCategoryOptionNone];
            [center setNotificationCategories:[NSSet setWithObject:category]];
            
            //第三步:设置推送方式
            UNTimeIntervalNotificationTrigger *timeTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:YES];
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestID content:content trigger:timeTrigger];
            
            //第四步:添加推送request
            [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                
            }];
            
            //移除推送
            [center removePendingNotificationRequestsWithIdentifiers:@[requestID]];
            [center removeAllDeliveredNotifications];
        }
    }
    

    参考文档:
    本地推送

    相关文章

      网友评论

          本文标题:iOS开发通知权限

          本文链接:https://www.haomeiwen.com/subject/zwdkultx.html