极光推送的快速集成

2017-04-19  本文已影响17人  Coder东

前言:
同事最近在做推送,我鉴于同事说推送消息会出现收不到的情况,我也自己对极光推送的知识点进行了回顾!!! 对于证书问题我就不再多,有疑问可以留言!!有错误请大神指正!!
#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;
}
上一篇下一篇

猜你喜欢

热点阅读