极光推送的快速集成

前言:
同事最近在做推送,我鉴于同事说推送消息会出现收不到的情况,我也自己对极光推送的知识点进行了回顾!!! 对于证书问题我就不再多,有疑问可以留言!!有错误请大神指正!!
#import "AppDelegate.h"
#import "RootViewController.h"
#import <TSMessage.h>

static NSString *appKey = @"3d23e44dd7fd08ea37588514";
static NSString *channel = @"Publish channel";
static BOOL isProduction = FALSE;


// 引 JPush功能所需头 件
#import "JPUSHService.h"
// iOS10注册APNs所需头 件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>



@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//激光推送配置
[self setJPUSHInfo:launchOptions  appliction:application];

RootViewController *rootVC = [RootViewController new];
self.window.rootViewController = rootVC;
[self.window makeKeyAndVisible];

 //杀死后点击icon进入时清除角标
application.applicationIconBadgeNumber = 0;
return YES;
}
//FIXME:MARK - - 推送设置 - -
-(void)setJPUSHInfo:(NSDictionary *)lunchOptions appliction:(UIApplication *)application {

JPUSHRegisterEntity *entity =[[ JPUSHRegisterEntity alloc]init];
entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;

[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

//如需使用IDFA功能请添加代码并在初始化方法的advertisingIdentifier参数中填写对应值
NSString *advertisingId = [[[ASIdentifierManager sharedManager]advertisingIdentifier]UUIDString];

[JPUSHService setupWithOption:lunchOptions appKey:appKey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];

//2.1.9版本新增获取registration id block接口。
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
    if(resCode == 0){
        NSLog(@"registrationID获取成功:%@",registrationID);
        
    }
    else{
        NSLog(@"registrationID获取失败,code:%d",resCode);
    }
}];

if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {

    UNUserNotificationCenter  *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:UNAuthorizationOptionCarPlay | UNAuthorizationOptionSound | UNAuthorizationOptionBadge | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"ios 10 request notification success");
        }else{
            NSLog(@"ios 10 request notification fail");
        }
    }];
}else if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0){
    
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert categories:nil];
}else{
    // ios <= 7.0
    
    UIRemoteNotificationType type = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
    [application registerForRemoteNotificationTypes:type];
}

[[UIApplication sharedApplication]registerForRemoteNotifications];
}
//FIXME:MARK -- 注册成功并上传deviceToken --
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
//required - 注册 DeviceToken
//注册推送成功,并上报deviceToken
[JPUSHService registerDeviceToken:deviceToken];
}
//FIXME:MARK -- 实现注册失败 --
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
//Optional
NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

//FIXME:MARK -- JPUSHRegisterDlegate--
//当应用在前台时,接收到通知消息首先会调用下面的方法 ios10以后
-(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]]) {
    //@abstract 处理收到的 APNs 消息
    [JPUSHService handleRemoteNotification:userInfo];
    }


if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    
    // 需要执 这个 法,选择 是否提醒 户,有Badge、Sound、Alert三种类型可以选择设置
    completionHandler(UNNotificationPresentationOptionSound);
    //当前应用在前台 接到通知
    NSString *messageAlert = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
    //获取顶层控制器
    UIViewController *curentVC = [self currentViewController];

    NSLog(@"messagetAlert--%@--%@",messageAlert,curentVC);
    
}else if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground){ //后台
    
    completionHandler(UNNotificationPresentationOptionAlert);
    NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
}else{//未启动
    
    completionHandler(UNNotificationPresentationOptionAlert);
    NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
    }

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
}
}

-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{

NSDictionary * userInfo = response.notification.request.content.userInfo;
if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);

}
completionHandler(); // 系统要求执 这个 法

}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
// Required, iOS 7 Support
[JPUSHService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);

    }

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// Required,For systems with less than or equal to iOS6
[JPUSHService handleRemoteNotification:userInfo];

}

-(NSString *)logDic:(NSDictionary *)dic {
if (![dic count]) {
    return nil;
}
NSString *tempStr1 =
[[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                             withString:@"\\U"];
NSString *tempStr2 =
[tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString *tempStr3 =
[[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
NSString *str =
[NSPropertyListSerialization propertyListFromData:tempData
                                 mutabilityOption:NSPropertyListImmutable
                                           format:NULL
                                 errorDescription:NULL];
return str;
}
  - (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


    - (void)applicationWillEnterForeground:(UIApplication *)application {
    //从后台点击icon进入时清除角标
  application.applicationIconBadgeNumber = 0;
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}

//获取window当前显示的ViewController
-(UIViewController *)currentViewController{

UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
while (1) {
    //根据不同的页面切换方式,逐步取得最上层的viewController
    if ([vc isKindOfClass:[UITabBarController class]]) {
        vc = ((UITabBarController *)vc).selectedViewController;
    }
    if ([vc isKindOfClass:[UINavigationController class]]) {
        vc = ((UINavigationController *)vc).visibleViewController;
    }
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    }else{
        break;
    }
}
return vc;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容