iOS 远程推送APNS从0至发布-代码集成篇

说明

头文件

#import "AppDelegate.h"
#import "JPUSHService.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

//JPush
static NSString *const appKey = @"5a6e94518f6bd85ba173cf77";
static NSString *const channel = @"App Store";
static BOOL const isProduction = YES;

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

辅助测试的UI代码:


#pragma mark --------------------------------------------------------
#pragma mark observe & addView
- (void)networkDidReceiveMsg:(NSNotification *)note{
    
//    NSDictionary * userInfo = [note userInfo];
//    NSString *content = [userInfo valueForKey:@"content"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段,key是自己定义的
    
    NSString *text = @"NSNotification";
    [self addTestViewRed:text];
}

- (void)addTestViewYellow:(NSString *)text{
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.5];
    testView.yh_size = CGSizeMake(100, 100);
    testView.center = [UIApplication sharedApplication].keyWindow.center;
    UITextView *textView = [[UITextView alloc] init];
    textView.bounces = YES;
    textView.text = text;
    textView.frame = testView.bounds;
    textView.yh_height -= 20;
    [testView addSubview:textView];
    [self.window.rootViewController.view addSubview:testView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testGes:)];
    [testView addGestureRecognizer:tap];
}
- (void)addTestViewRed:(NSString *)text{
    UIView *testView = [[UIView alloc] init];
    testView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
    testView.yh_size = CGSizeMake(100, 100);
    testView.center = self.window.center;
    UITextView *textView = [[UITextView alloc] init];
    textView.bounces = YES;
    textView.text = text;
    textView.frame = testView.bounds;
    textView.yh_height -= 20;
    [testView addSubview:textView];
    [self.window.rootViewController.view addSubview:testView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testGes:)];
    [testView addGestureRecognizer:tap];
}
- (void)testGes:(UITapGestureRecognizer *)tapGes{
    
    [tapGes.view removeFromSuperview];
}

注册代码:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    application.applicationIconBadgeNumber = 0;
    //设置推送
    [self setupJPush:launchOptions];
    return YES;
}

//建立JPush
- (void)setupJPush:(NSDictionary *)launchOptions{
    
    
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //Required
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction];
    
    
    ///极光文档:只有在前端运行的时候才能收到自定义消息的推送。
   //笔者并没有测试到执行这个通知方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMsg:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    if (launchOptions) {
        
        NSString *alert = launchOptions[@"aps"][@"alert"];
        NSString *string = [NSString stringWithFormat:@"%@%@", @"有通知: setupJPush", alert];
        [self addTestViewRed:string];
    }
    
}

处理推送的各方法

#pragma mark ------------------------------------------
#pragma mark JPush methods
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSString *alert = userInfo[@"aps"][@"alert"];
    if (application.applicationState == UIApplicationStateActive) {
        YHLog(@"active,接收到远程通知userInfo--");
        
        application.applicationIconBadgeNumber = 0;
        
        ///接收到远程通知后的操作
        NSString *text = [NSString stringWithFormat:@"%@%@", @"fetchCompletionHandler -- UIApplicationStateActive---", alert];
        [self addTestViewRed:text];
        
    }else if(application.applicationState == UIApplicationStateBackground){
        //程序处于后台,推送时不勾选`content avaliable` 时没有这个模式
        NSString *text = [NSString stringWithFormat:@"%@%@", @"fetchCompletionHandler -- UIApplicationStateBackground---", alert];
        [self addTestViewRed:text];
        
    }else if (application.applicationState == UIApplicationStateInactive){
        YHLog(@"UIApplicationStateInactive");
        
        ///接收到远程通知后的操作
        NSString *text = [NSString stringWithFormat:@"%@%@", @"fetchCompletionHandler -- UIApplicationStateInactive---", alert];

        [self addTestViewRed:text];
    }
    
    //     IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
    
    NSString *text = [NSString stringWithFormat:@"%@%@", @"JPUSHRegisterDelegate -- willPresentNotification---", userInfo[@"aps"][@"alert"]];
    [self addTestViewYellow:text];
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    
    NSString *text = [NSString stringWithFormat:@"%@%@", @"JPUSHRegisterDelegate -- didReceiveNotificationResponse---", userInfo[@"aps"][@"alert"]];
    [self addTestViewYellow:text];
    
}

不同情况下调用的方法总结

iOS 10

1.应用在前台,

1.1 没有设置 content-available ,
  • 1.1.1 调用JPUSHRegisterDelegate 方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
willPresentNotification:(UNNotification *)notification 
withCompletionHandler:(void (^)(NSInteger))completionHandler
  • 1.1.2 如果此时点击了通知栏,会再调用下 JPUSHRegisterDelegate 方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
withCompletionHandler:(void (^)())completionHandler
1.2 设置了 content-available ,
  • 1.2.1 先调用方法, 其中application.applicationState == UIApplicationStateActive
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  • 1.2.2 再调用方法 JPUSHRegisterDelegate 方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
willPresentNotification:(UNNotification *)notification 
withCompletionHandler:(void (^)(NSInteger))completionHandler
  • 1.2.3 如果此时点击了通知,会再调用下 JPUSHRegisterDelegate 方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
withCompletionHandler:(void (^)())completionHandler 

2.应用在后台,

2.1 没有设置 content-available :
  • 2.1.1 用户没有点击通知栏打开的app,不可以拦截.且app切换至前台后,通知栏消失.
  • 2.1.2 如果用户点击了通知栏,就可以拦截.调用 JPUSHRegisterDelegate 方法:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
withCompletionHandler:(void (^)())completionHandler 
2.2 设置 content-available :
  • 2.2.1 调用方法, 其中 application.applicationState == UIApplicationStateBackground
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 
  • 2.2.2 如果用户点击app图标打开的app,则当前通知栏的这条通知自动消失; 如果用户点击通知栏打开的app,会再调用下方法:
 - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
withCompletionHandler:(void (^)())completionHandler

3.应用由死到生,

3.1 无论是否设置 content-available ,
  • 3.1.1 点击通知栏打开, 依次调用方法:
    1. 方法一
 - (BOOL)application:(UIApplication *)application 
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    1. 方法二 JPUSHRegisterDelegate :
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response 
withCompletionHandler:(void (^)())completionHandler 
  • 3.1.2 点击app图标打开app,则拦截不到通知.此时 launchOptions 也为空. 个人认为这正常,app从死到生,所以是正常的过程,不需要也拿不到通知信息.

一. iOS 9

应用在前台,

无论是否设置 content-available , 都会调用方法,其中 application.applicationState == UIApplicationStateActive
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

应用在后台,

没有设置 content-available , 有通知栏提示
  • 2.1.1 点击通知栏会调用方法,其中 application.applicationState == UIApplicationStateInactive
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  • 2.1.2 不点击通知栏,或点击图标打开app,都不会调用上通知处理方法
2.2 设置 content-available , 有通知栏提示
    1. 调用方法,其中 application.applicationState == UIApplicationStateBackground
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    1. 如果点击了通知栏, 会再次调用这个方法,其中 application.applicationState == UIApplicationStateInactive
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

应用由死到生,

3.1 无论是否设置 content-available
  • 3.1.1 点击通知栏打开app, 依次调用方法:
    1. 方法一
  - (BOOL)application:(UIApplication *)application 
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
  • 2)方法二, 其中 application.applicationState == UIApplicationStateInactive
- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  • 3.1.2 点击app图标打开app,则拦截不到通知.此时 launchOptions 也为空. 个人认为这正常,app从死到生,所以是正常的过程,不需要也拿不到通知信息.

注: 转载就注明出处: http://www.jianshu.com/p/9e2464be0fd5

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,579评论 18 139
  • 极光推送: 1.JPush当前版本是1.8.2,其SDK的开发除了正常的功能完善和扩展外也紧随苹果官方的步伐,SD...
    Isspace阅读 6,694评论 10 16
  • 推送通知 注意:这里说的推送通知跟NSNotification有所区别 NSNotification是抽象的,不可...
    iOS开发攻城狮阅读 4,185评论 1 13
  • 不同版本极光推送SDK集成各有差异,集成时一定要注意版本号,楼主已将博文更新成最新的SDK JPush v3.0....
    i顺颂时宜阅读 7,840评论 37 170
  • 引言:iOS开发,推送可以说是必须的,但是之前对于推送总是概念模糊,最近借公司项目需求,深入了解了一下。“对于知识...
    ibabyblue阅读 1,333评论 36 8