极光推送集成开发

1.极光推送集成与设置

极光推送地址
①注册极光推送账号。
②在应用管理内按照步骤创建APP。
③找到“文档——iOS——iOS证书设置指南”内容,根据iOS证书设置指南,在苹果开发中心,生成开发环境证书与生产环境证书,导出并且配置极光后台管理(推送设置)。
④下载文档,集成到项目中。根据“文档——iOS——iOS SDK集成指南”将极光的资源文件以及配制信息设置完成。

2.项目内代码

①在AppDelegate.m中导入极光推送头文件

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import 
#endif
//如果需要使用idfa功能所需要引入的头文件(可选)
//#import 

②注册极光推送服务并调用代理方法

@interface AppDelegate ()
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
//极光推送
    //notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet *categories for iOS10 or later
        // NSSet *categories for iOS8 and iOS9
    }
    //实现极光代理方法
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    
    // init Push 初始化推送
    // notice: 2.1.5版本的SDK新增的注册方法,改成可上报IDFA,如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容,请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"a7601f4c7f018afee89d57c1"
                          channel:@"App Store"
                 apsForProduction:1
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功:%@",registrationID);
        }
        else{
            NSLog(@"registrationID获取失败,code:%d",resCode);
        }
    }];

}

③实现极光代理方法(包含版本兼容以及前台后台收到推送消息,做对应页面跳转功能)

#pragma mark -
#pragma mark JPUSHRegisterDelegate
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional -注册失败
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    //[self showAlertViewMessage:@"1"];
    //Required
    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]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    //[self showAlertViewMessage:@"2"];
    //Required
    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]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    
        [self jumpToViewControllerApplication:nil userInfo:userInfo];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@,\ntitle:%@,\nsubtitle:%@,\nbadge:%@,\nsound:%@,\nuserInfo:%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler();// 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    //[self showAlertViewMessage:@"3"];
    //Required,iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    DLog(@"字典内容是:%@",userInfo);
    
    // 应用在前台 或者后台开启状态下,不跳转页面,让用户选择。
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground)
    {
        //[self showAlertViewMessage:@"5"];
        NSLog(@"acitve or background");
        //应用处于前台收到推送的时候
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"钢圈提示" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alertView show];
    }
    else//杀死状态下,直接跳转到想要跳转的页面。
    {
        //[self showAlertViewMessage:@"6"];
        Singleton * singleton = [Singleton singleton];
        NSDictionary * jsonDic = [self dictionaryWithJsonString:[userInfo objectForKey:@"mainType"]];
        //不在这里做跳转,只是保存远程推送给的信息,在进入了页面的时候跳转对应页面
        if ([jsonDic[@"info"] isEqualToString:@"order"])
        {
            NSString * extrasStr = [self stringWithJsonString:[userInfo objectForKey:@"extras"]];
            //订单详情页面
            singleton.tabbar = @"0";
            singleton.page = @"1";
            singleton.orderID = extrasStr;
            singleton.badge = [userInfo[@"aps"][@"badge"] integerValue];
        }
        //用于点击推送消息进入app时,tabbar选择以及跳转的代码设置(主要是tabbar已经创建,不会按照正常层级关系进入app,这里做特殊设置改变app状态)
        self.mainTabbarCtl = [MainTabbarViewController new];
        self.mainTabbarCtl.selectedIndex = singleton.tabbar.integerValue;
        //[self.mainTabbarCtl.tabbar selectIndex:singleton.tabbar.integerValue];
        self.window.rootViewController = self.mainTabbarCtl;
        [self chooseRootController:self.mainTabbarCtl];
        
        
        //每次点击一个消息就消失一个
//        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:[userInfo[@"aps"][@"badge"] integerValue]-1];
//        [JPUSHService setBadge:[userInfo[@"aps"][@"badge"] integerValue]-1];
    }
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //[self showAlertViewMessage:@"4"];
    //Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark - 跳转到指定界面(iOS10)
-(void)jumpToViewControllerApplication:(UIApplication *)application userInfo:(NSDictionary *)userInfo
{
    // 应用在前台 或者后台开启状态下,不跳转页面,让用户选择。
//    if (application.applicationState == UIApplicationStateActive)
//    {
//        NSLog(@"acitve or background");
//        //应用处于前台收到推送的时候
//        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"钢圈提示" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即查看", nil];
//        [alertView show];
//    }
//    else//杀死状态下,直接跳转到想要跳转的页面。
//    {
//        //        WGLoginController *VC = [WGLoginController new];
//        //        UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:VC];
//        //        [self.mainTabbarCtl presentViewController:VC animated:YES completion:nil];
//        //不在这里做跳转,只是发送通知消息,在进入了页面的时候跳转对应页面
//        if ([userInfo[@"mainType"] isEqualToString:@"order"] )
//        {
//            notificationDic = @{@"tabbar":@"0", @"page":@"1"};//订单页面
//        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"tiaozhuan" object:nil userInfo:notificationDic];
//    }
    
    Singleton * singleton = [Singleton singleton];
    NSDictionary * jsonDic = [self dictionaryWithJsonString:[userInfo objectForKey:@"mainType"]];
    //不在这里做跳转,只是保存远程推送给的信息,在进入了页面的时候跳转对应页面
    if ([jsonDic[@"info"] isEqualToString:@"order"])
    {
        NSString * extrasStr = [self stringWithJsonString:[userInfo objectForKey:@"extras"]];
        //订单详情页面
        singleton.tabbar = @"0";
        singleton.page = @"1";
        singleton.orderID = extrasStr;
    }
    //用于点击推送消息进入app时,tabbar选择以及跳转的代码设置(主要是tabbar已经创建,不会按照正常层级关系进入app,这里做特殊设置改变app状态)
    self.mainTabbarCtl = [MainTabbarViewController new];
    self.mainTabbarCtl.selectedIndex = singleton.tabbar.integerValue;
    //[self.mainTabbarCtl.tabbar selectIndex:singleton.tabbar.integerValue];
    self.window.rootViewController = self.mainTabbarCtl;
    [self chooseRootController:self.mainTabbarCtl];
}
#pragma mark-
#pragma JSON字符串转化为字典
//JSON字符串转化为字典
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return dic;
}
//JSON字符串转化为字符串(截取字符串方式)
-(NSString *)stringWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSString * string = jsonString;
    NSRange range = NSMakeRange(1, string.length-2);
    string = [string substringWithRange:range];
    return string;
}
#pragma mark -
#pragma mark 消息提醒(方法是否进入提醒)
-(void)showAlertViewMessage:(NSString *)message
{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"进入方法提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

3.总结

①极光推送包含跳转对应页面、推送badges数正确显示功能。可以点击跳转浏览详细文章。
②极光推送在合适的位置消角标

//app角标
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:badges];
//向服务器发送推送角标清零请求操作
//极光推送设置清角标
[JPUSHService setBadge:badges];

你可能感兴趣的:(极光推送集成开发)