iOS 10 極光推送JPush iOS SDK v2.1.9的用法

更新時間

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 的極光推送的全部內容了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 因為要結局swift3.0中引用snapKit的問題,看到一篇介紹Xcode8,swift3變化的文章,覺得很詳細...
    uniapp閱讀 4,537評論 0 12
  • 首先用cocoapods導入 pod 'JPush' 然后在AppDelegate引用 // 引入JPush功能所...
    MoneyLee閱讀 2,100評論 0 1
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,544評論 25 708
  • 一馬沖千騎,當陽救主還。 忠肝昭日月,義膽嘯河山。 勒馬敵心怯,橫槍賊膽寒。 功隨名長耀,勇與武相傳。
    霙愔閱讀 543評論 13 6
  • Python 字典 映射類型對象里哈希值(鍵,key)和指向的對象(值,value)是一對多的的關系,通常被認為是...
    阿帕零閱讀 216評論 0 1