jpushiOS 实用

iOS 10 极光推送JPush iOS SDK v2.1.9的

2016-11-11  本文已影响0人  繁华乱世沧桑了谁的容颜

更新时间

2016-09-07
新增:全面支持 iOS 10 新特性。
修复bug:增加SDK的稳定性。
优化改进:新增获取registrationID的接口,TagAlias支持设置特殊字符。
优化改进:SDK全部使用HTTPS链接。
说白了就是为了配合苹果要求的HTTPS(2017.1.1理论上全面禁止HTTP)
导入头文件:#import "JPUSHService.h"

import

import

记得声明代理 JPUSHRegisterDelegate
直接上代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //注册推送
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
    //可以添加自定义categories
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
} 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];
}
//1 初始化
[JPUSHService setupWithOption:launchOptions appKey:@"6e6a89d85baa1be6ea0fc8c5"
                      channel:@"App Store"
             apsForProduction:YES];


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

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

[JPUSHService setAlias:[USER_DEFAULT objectForKey:@"memberId"] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:nil];

}
- (void)testRemoveNotification {
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
{
    JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
    identifier.identifiers = @[@"sampleRequest"];
    identifier.delivered = YES;  //iOS10以上有效,等于YES则在通知中心显示的里面移除,等于NO则为在待推送的里面移除;iOS10以下无效
    [JPUSHService removeNotification:identifier];
}
else
{
    [JPUSHService removeNotification:nil];  // iOS10以下移除所有推送;iOS10以上移除所有在通知中心显示推送和待推送请求

}

}

- (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 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(); // 系统要求执行这个方法

}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
NSLog(@"你是我的09999999");

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;  // 推送消息的标题
[self testRemoveNotification];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[JPUSHService setBadge:0];
if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    NSLog(@"iOS10 前台收到远程通知:%@", userInfo);
}
else {
    // 判断为本地通知
    NSLog(@"iOS10 前台收到本地通知:{\\nbody:%@,\\ntitle:%@,\\nsubtitle:%@,\\nbadge:%@,\\nsound:%@,\\nuserInfo:%@\\n}",body,title,subtitle,badge,sound,userInfo);
}
completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
// 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以设置

}

值得注意的是上面那个方法只会在iOS10的系统上面才会执行,不知道以后会不会改,所以对于没有升级iOS10的用户只写到这里是不够的还需要下面的一个方法
//iOS10以下

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"你是我的6666666");

[JPUSHService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
int badge =[userInfo[@"aps"][@"badge"] intValue];
badge--;
[JPUSHService setBadge:badge];
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;

// 上面几行是文档自带的



// 1、应用正处在前台状态下,不会收到推送消息,这里创建一个UIAlertController来接受消息
NSLog(@"userInfo333通知---:%@", userInfo);

if (application.applicationState == UIApplicationStateActive) {
    UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"新消息" message:userInfo[@"aps"][@"alert"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* updateAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@"查看了");
        [self jumpVC];


    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertvc addAction:cancelAction];
    [alertvc addAction:updateAction];
    [self.window.rootViewController presentViewController:alertvc animated:YES completion:nil];
} else if (application.applicationState == UIApplicationStateInactive)
{
    // 处于后台运行状态时
    NSLog(@"---UIApplicationStateInactive处于后台运行状态时---");

    
    [self jumpVC];
}
else if (application.applicationState == UIApplicationStateBackground)
{
    [self jumpVC];

}
    // badge清零
 [JPUSHService setBadge:0];
//    [application setApplicationIconBadgeNumber:0];
//    [JPUSHService resetBadge];

}

下面介绍点击通知跳转的具体方法
// 获取当前处于activity状态的view controller
- (UIViewController *)activityViewController
{
UIViewController *activityViewController = nil;

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
if(window.windowLevel != UIWindowLevelNormal)
{
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for(UIWindow *tmpWin in windows)
    {
        if(tmpWin.windowLevel == UIWindowLevelNormal)
        {
            window = tmpWin;
            break;
        }
    }
}

NSArray *viewsArray = [window subviews];
if([viewsArray count] > 0)
{
    UIView *frontView = [viewsArray objectAtIndex:0];
    
    id nextResponder = [frontView nextResponder];
    
    if([nextResponder isKindOfClass:[UIViewController class]])
    {
        activityViewController = nextResponder;
    }
    else
    {
        activityViewController = window.rootViewController;
    }
}

return activityViewController;

}
UITabBarController *tabBarVC = (UITabBarController *)[self activityViewController];
navc = (NavigationViewController *)tabBarVC.selectedViewController;
// 上面几行是文档自带的



// 1、应用正处在前台状态下,不会收到推送消息,这里创建一个UIAlertController来接受消息
NSLog(@"userInfo333通知---:%@", userInfo);

if (application.applicationState == UIApplicationStateActive) {
    UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"新消息" message:userInfo[@"aps"][@"alert"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* updateAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            ActiveViewController *aVC = [[ActiveViewController alloc]initWithRemoteNotification:userInfo];
  //            UINavigationController *nav = (UINavigationController*)     (self.window.rootViewController);
//            [nav pushViewController:aVC animated:YES];
        NSLog(@"查看了");
        [self jumpVC];


    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertvc addAction:cancelAction];
    [alertvc addAction:updateAction];
    [self.window.rootViewController presentViewController:alertvc animated:YES completion:nil];
} else if (application.applicationState == UIApplicationStateInactive)
{
    // 处于后台运行状态时
    NSLog(@"---UIApplicationStateInactive处于后台运行状态时---");
    
//        OrderInfoViewController *ivc=[[OrderInfoViewController alloc]init];
////        NavigationViewController *nav = (NavigationViewController*) (self.window.rootViewController);
//        [navc pushViewController:ivc animated:YES];
    
    [self jumpVC];
}
else if (application.applicationState == UIApplicationStateBackground)
{
    [self jumpVC];

}

以上就是iOS10 的极光推送的全部内容了

上一篇下一篇

猜你喜欢

热点阅读