JPush推送之当进程被终止的处理

当系统通知栏接收到JPush远程推送消息,并实现点击消息跳转指定页面,处理推送消息的回调函数如下:

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        if (userInfo) {
            [self push:userInfo];
        }else{
            return;
        }
        [JPUSHService handleRemoteNotification:userInfo];
    }
    else {
    }
    completionHandler();  // 系统要求执行这个方法
}

一、我们需要分析有哪些跳转的情景:

1、程序在前台运行时接收到消息
2、程序在后台运行时接收到消息
3、程序处于终止(杀死)状态下接收到消息

那么本文重点来探讨下当程序处于终止状态下时接收到消息如何处理?

不设悬念直入主题吧,仿照QQ、微信等其他APP的推送机制可以了解到,当程序被终止状态下,点击通知栏的消息只打开app并不能跳转特定页面,原因是appDelegate的main函数不执行,那么Push的载体导航器也不存在。系统只能根据通知栏所点击消息对应远程推送注册码来选择启动哪一个APP.

所以消息处理的逻辑即:

1、程序未被终止状态下,编写正常跳转特定页面的代码
2、程序被终止状态下,屏蔽Push跳转代码,只启动app即可

二、问题来了,进程被终止回调机制是什么呢?

1、程序进程被终止会调用此函数

// 程序进程被终止时调用
- (void)applicationWillTerminate:(UIApplication *)application{
    [[NSUserDefaults standardUserDefaults] setObject:applicationWillTerminate forKey:applicationWillTerminate];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

需要注意:此回调函数不能主动被调起,还需要在程序进入后台的回调函数中开启UIBackgroundTaskIdentifier任务,即如下操作

2、声明全局变量

UIBackgroundTaskIdentifier _bgTask;

3、开启后台任务

- (void)applicationDidEnterBackground:(UIApplication *)application {    
    _bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        // Synchronize the cleanup call on the main thread in case
        // the task actually finishes at around the same time.
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_bgTask != UIBackgroundTaskInvalid)
            {
                [[UIApplication sharedApplication] endBackgroundTask:_bgTask];
                _bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
}

亦可在程序进入后台执行一些保存、清理操作

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){
//程序在10分钟内未被系统关闭或者强制关闭,则程序会调用此代码块,可以在这里做一些保存或者清理工作
NSLog(@"程序关闭");
}];
三、如何判断当前的程序是否已经被终止呢?

显然普通的BOOL或者属性记录是行不通的,appDelegate的代码就不执行,那么找到的解决方案是:轻量级存储。

1、定义常量

// 定义当前程序被终止常量
static NSString *const applicationWillTerminate = @"applicationWillTerminate";

2、记录进程被强制终止

// 程序进程被终止时调用
- (void)applicationWillTerminate:(UIApplication *)application{
    [[NSUserDefaults standardUserDefaults] setObject:applicationWillTerminate forKey:applicationWillTerminate];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

3、当已启动进程时remove掉存储对象。

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:applicationWillTerminate];
    [[NSUserDefaults standardUserDefaults] synchronize];

四、runtime处理推送消息跳转特定页面源码
- (void)push:(NSDictionary *)userInfo
{
    NSDictionary *params;
    if ([[NSString stringWithFormat:@"%@",userInfo[@"aps"][@"badge"]] isEqualToString:@"1"]) {
        //邀请面试
        params = @{
                   @"class": @"InterviewTimeViewController",
                   @"property": @{
                           @"ID": @"123",
                           @"channelType": @"12"
                           }
                   };
    }else if ([[NSString stringWithFormat:@"%@",userInfo[@"extrasKey"]] isEqualToString:@"0"]){
        //查看简历状态
        params = @{
                   @"class": @"ResumeStateViewController",
                   @"property": @{
                           @"ID": @"234",
                           @"channelType": @"13"
                           }
                   };
    }

    // 类名
    NSString *classStr =[NSString stringWithFormat:@"%@", params[@"class"]];
    const char *className = [classStr cStringUsingEncoding:NSASCIIStringEncoding];
    
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass)
    {
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }
    // 创建对象
    id instance = [[newClass alloc] init];
    
    // 对该对象赋值属性
    NSDictionary * propertys = params[@"property"];
    [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 检测这个对象是否存在该属性
        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
            // 利用kvc赋值
            [instance setValue:obj forKey:key];
        }
    }];
    
    NSString *terminate = [[NSUserDefaults standardUserDefaults] objectForKey:applicationWillTerminate];
    if (![terminate isEqualToString:applicationWillTerminate]) {
        // 获取导航控制器
        UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
        UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
        // 跳转到对应的控制器
        [pushClassStance pushViewController:instance animated:YES];
    }
}



- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance
                                                           class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    
    return NO;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容