iOS 远程推送消息解析及逻辑处理

时间:2021-10-17 08:35:43

关于远程推送的相关配置网上已经有足够多的教程,这里就不复述了。这里讲述当客户端收到推送消息后,应怎样对其进行相应的逻辑处理。

工程的AppDelegate.m文件里提供了如下方法:

//当应用程序启动后,可能需要进行其他逻辑处理时调用的方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
//成功注册registerUserNotificationSettings:后,回调的方法
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings;
/// 注册失败调用
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
/// 用户同意接收通知后,会调用此程序
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
//收到推送后调用的方法(iOS 10 及以上)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler;
//收到推送后调用的方法(iOS 10 以下)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
//应用挂起前调用的方法(当有电话进来或者锁屏,应用会挂起)
- (void)applicationWillResignActive:(UIApplication *)application;
//当程序复原或启动时调用的方法
- (void)applicationDidBecomeActive:(UIApplication *)application;
//应用将要进入后台调用的方法
- (void)applicationWillEnterForeground:(UIApplication *)application;
//应用进入后台调用的方法
-(void)applicationDidEnterBackground:(UIApplication *)application;
//应用将要退出
- (void)applicationWillTerminate:(UIApplication *)application;

首先为应用程序注册通知:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *remoteNotification = [launchOptions objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    if (remoteNotification != nil) {
        self.isLaunchedByNotification = YES;
    }else{
        self.isLaunchedByNotification = NO;
    }
    self.window=[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"succeeded!");
            }
        }];
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){//iOS8-iOS9
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        [application registerUserNotificationSettings:settings];
        [application registerForRemoteNotifications];
    } else {//iOS8以下
        [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
    }
    return YES;
}

用户同意后,会调用此程序,获取系统的deviceToken,应把deviceToken传给服务器保存,此函数会在程序每次启动时调用(前提是用户允许通知):

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"deviceToken = %@",deviceToken);
    NSString *token=[NSString stringWithFormat:@"%@",deviceToken];
    token=[token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token=[token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token=[token stringByReplacingOccurrencesOfString:@" " withString:@""];
    //TODO
    //保存到本地并上传到服务器
}

收到推送消息后,进行相应的逻辑处理:

//iOS 10 及以上
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    completionHandler(UIBackgroundFetchResultNewData);
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    //程序关闭状态点击推送消息打开
    if (self.isLaunchedByNotification) {
        //TODO
    }
    else{
        //前台运行
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            //TODO
        }
        //后台挂起时
        else{
            //TODO
        }
        //收到推送消息手机震动,播放音效
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        AudioServicesPlaySystemSound(1007);
    }
    //设置应用程序角标数为0
    [UIApplication sharedApplication].applicationIconBadgeNumber = 9999;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

//iOS 10 以下
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    completionHandler(UIBackgroundFetchResultNewData);
    //程序关闭状态点击推送消息打开
    if (self.isLaunchedByNotification) {
        //TODO
    }
    else{
        //前台运行
        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
            //TODO
        }
        //后台挂起时
        else{
            //TODO
        }
        //收到推送消息手机震动,播放音效
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        AudioServicesPlaySystemSound(1007);
    }
    //设置应用程序角标数为0
    [UIApplication sharedApplication].applicationIconBadgeNumber = 9999;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

应用进入后台时,设置角标数(应用图标右上角小红点,未读消息数):

-(void)applicationDidEnterBackground:(UIApplication *)application{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:123];
}