极光推送集成

推送对于想在的App来说基本是必备的,但是很多时候大家可能都是一股脑的写到Appdelegate类文件中,不能说不好,只是对于我这样的强迫症和外加一点点的懒的人来说,并不喜欢这样的。出于对功能模块化的考虑,特此将推送整体做了一个封装。代码如下:
.h中

#import "AppDelegate.h"

@interface AppDelegate (MEJPush) <JPUSHRegisterDelegate>

- (void)JPushApplication:(UIApplication *_Nullable)application didFinishLaunchingWithOptions:(NSDictionary *_Nullable)launchOptions;

/// 获得Device Token
- (void)JPushApplication:(UIApplication *_Nullable)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *_Nullable)deviceToken;

/// 获得Device Token失败
- (void)JPushApplication:(UIApplication *_Nullable)application didFailToRegisterForRemoteNotificationsWithError:(NSError *_Nullable)error;

/// iOS 7 以上远程推送消息回调
- (void)JPushApplication:(UIApplication *_Nullable)application didReceiveRemoteNotification:(NSDictionary *_Nullable)userInfo fetchCompletionHandler:(void (^_Nullable)(UIBackgroundFetchResult result))completionHandler;

/// iOS 8 远程推送消息回调
- (void)JPushApplication:(UIApplication *_Nullable)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *_Nullable)userInfo completionHandler:(void(^_Nullable)())completionHandler;

/// iOS 9 远程推送消息回调
- (void)JPushApplication:(UIApplication *_Nullable)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *_Nullable)userInfo withResponseInfo:(NSDictionary *_Nullable)responseInfo completionHandler:(void(^_Nullable)())completionHandler;

@end

.m中
#import "AppDelegate+MEJPush.h"
#import "MessageManageViewController.h"

 //是否为开发环境
static BOOL isProduction = FALSE;

@implementation AppDelegate (MEJPush)

#pragma mark - 注册推送
- (void)registerRemoteNotification:(NSDictionary *)launchOptions {
    if (UI_IS_IOS10_AND_HIGHER) {
        //极光推送
        //notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    } else if (UI_IS_IOS8_AND_HIGHER) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];

    }

#warning TODO 上线和测试 分别使用FALSE 和 YES
    [JPUSHService setupWithOption:launchOptions
                           appKey:kJPush_AppKey
                          channel:kJPush_channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];

    //设置推送日志
    [JPUSHService setDebugMode];

    // 极光推送添加观察者
    NSNotificationCenter *defaultCenter1 = [NSNotificationCenter defaultCenter];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkIsConnecting:)
                           name:kJPFNetworkIsConnectingNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkDidSetup:)
                           name:kJPFNetworkDidSetupNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkDidClose:)
                           name:kJPFNetworkDidCloseNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkDidRegister:)
                           name:kJPFNetworkDidRegisterNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkFailedRegister:)
                           name:kJPFNetworkFailedRegisterNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkDidLogin:)
                           name:kJPFNetworkDidLoginNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(networkDidReceiveMessage:)
                           name:kJPFNetworkDidReceiveMessageNotification
                         object:nil];
    [defaultCenter1 addObserver:self
                       selector:@selector(serviceError:)
                           name:kJPFServiceErrorNotification
                         object:nil];
}  

#pragma mark - 监听推送
- (void)JPushApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self registerRemoteNotification:launchOptions];

    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification) {
        NSLog(@"%@",remoteNotification);
        [self goToMssageViewControllerWith:launchOptions];
    }
    // 重新设置app角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // 重新设置角标
    [JPUSHService resetBadge];
}

/// 获得Device Token
- (void)JPushApplication:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSLog(@"deviceToken---%@",[NSString stringWithFormat:@"%@",deviceToken]);
    //极光注册设备
    [JPUSHService registerDeviceToken:deviceToken];
}

/// 获得Device Token失败
- (void)JPushApplication:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

/// iOS 7 以上远程推送消息回调(不能处理带有categories的推送消息)
- (void)JPushApplication:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];  //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音

    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的
    NSLog(@"content =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,(long)badge,sound,customizeField1);
    [self goToMssageViewControllerWith:aps];
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

/// iOS 8 远程推送消息回调
- (void)JPushApplication:(UIApplication *_Nullable)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *_Nullable)userInfo completionHandler:(void(^_Nullable)())completionHandler {
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音

    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的
    NSLog(@"content =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,(long)badge,sound,customizeField1);
    [self goToMssageViewControllerWith:aps];
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

/// iOS 9 远程推送消息回调
- (void)JPushApplication:(UIApplication *_Nullable)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *_Nullable)userInfo withResponseInfo:(NSDictionary *_Nullable)responseInfo completionHandler:(void(^_Nullable)())completionHandler {
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音

    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的
    NSLog(@"content =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,(long)badge,sound,customizeField1);
    [self goToMssageViewControllerWith:aps];
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

#pragma mark - iOS 10 以上将本地和远程推送合而为一,并且增加了接受和点击事件
/// 接收事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center  willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {

    NSDictionary *userInfo = notification.request.content.userInfo;
//    UNNotificationRequest *request = 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 ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 前台收到远程通知:%@", userInfo);
        [JPUSHService handleRemoteNotification:userInfo];
    } else {
        // 本地通知
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

/// 点击事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
    // Required
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSDictionary *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音

    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"content =[%@], badge=[%ld], sound=[%@]",content,(long)badge,sound);
        [self goToMssageViewControllerWith:aps];
        [JPUSHService handleRemoteNotification:userInfo];
    } else {
        // 本地通知
    }
    completionHandler();  // 系统要求执行这个方法
}

#pragma mark - 极光推送监听事件
/// 推送正在连接
- (void)networkIsConnecting:(NSNotification *)notification {
    NSLog(@"正在连接 %@", [notification userInfo]);
}

/// 推送建立连接
- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"建立连接 %@", [notification userInfo]);
}

/// 推送关闭连接
- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"关闭连接 %@", [notification userInfo]);
}

/// 推送注册成功
- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"注册成功 %@", [notification userInfo]);
}

/// 推送注册失败
- (void)networkFailedRegister:(NSNotification *)notification {
    NSLog(@"注册失败 %@", [notification userInfo]);
}

/// 推送登录成功
- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录  %@", [notification userInfo]);
     //存储极光推送的registrationID
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if (resCode != 1011) {
            if (registrationID) {
                 [MELoginInfo saveJpushRegistrationID:[JPUSHService registrationID]];
            }
        }
    }];
}

/// 接收到推送消息 (非远程推送消息)
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSLog(@"收到消息(非APNS) %@", [notification userInfo]);
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *remind = [extras objectForKey:@"extras"];//服务端传递的Extras附加字段,key是自己定义的

    NSString *message = [NSString stringWithFormat:@"%@, 本次推送的内容为:%@", remind, content];
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"APNs自定义推送消息" message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
    }];
    [alterController addAction:alertAction];

    [self.window.rootViewController presentViewController:alterController animated:YES completion:nil];
}

//接收到推送消息 (非远程推送消息)
- (void)kJPFNetworkDidReceiveMessageNotification:(NSNotification *)notification {
    NSLog(@"%@",notification);
}

/// 推送错误
- (void)serviceError:(NSNotification *)notification {
    NSLog(@"极光推送错误 %@", [notification userInfo]);
}

#pragma mark - 跳转界面
- (void)goToMssageViewControllerWith:(NSDictionary *)userInfo {
    if (userInfo.count > 0) {
        [MELoginInfo saveJpushReceiveData:userInfo];
        NSString *isPush = [userInfo objectForKey:@"isPush"];
        if ([isPush isEqualToString:@"1"]) {
            [self displayLoginViewControllerWithIdentifier:@"MessageManage_VC"];
        }
    }
}

#pragma mark - 加载storyboard控制器的公共方法(未登录界面)
- (void)displayLoginViewControllerWithIdentifier:(NSString *)identifier {
    UINavigationController *nav = [[UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:identifier];
    [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
}

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,837评论 25 707
  • 极光推送: 1.JPush当前版本是1.8.2,其SDK的开发除了正常的功能完善和扩展外也紧随苹果官方的步伐,SD...
    Isspace阅读 6,704评论 10 16
  • 前面花了很多篇幅介绍的JUnit和Mockito,它们都是针对Java全平台的一些测试框架。写到这里,咱们开始介绍...
    云飞扬1阅读 5,655评论 0 48
  • 我舍不得的那个世界里,我爱的人其实早已走远。一生戎马也倒戈爱恨,叱咤风云终究躲不过一颗心,也许,这世界上就没有什么...
    草絮阅读 267评论 0 0
  • 1. 爱情,它可以吃吗? 不,爱情吃了就没有了 会变成屎 爱情应该是仙女 不着凡尘,...
    癫狂撒哈拉阅读 183评论 0 2