iOS推送(利用極光推送),ios極光

來源:互聯網
上載者:User

iOS推送(利用極光推送),ios極光

本文主要是基於極光推送的SDK封裝的一個快速整合極光推送的類的封裝(不喜勿噴)

 

(1)首先說一下推送的一些原理:

Push的原理:

Push 的工作機制可以簡單的概括為

圖中,Provider是指某個iPhone軟體的Push伺服器,這篇文章我將使用.net作為Provider。 
APNS 是Apple Push Notification Service(Apple Push伺服器)的縮寫,是蘋果的伺服器。

可以分為三個階段。

第一階段:.net應用程式把要發送的訊息、目的iPhone的標識打包,發給APNS。 
第二階段:APNS在自身的登入Push服務的iPhone列表中,尋找有相應標識的iPhone,並把訊息發到iPhone。 
第三階段:iPhone把發來的訊息傳遞給相應的應用程式, 並且按照設定彈出Push通知。

 

    從我們可以看到。

   1、首先是應用程式註冊訊息推送。

   2、 IOS跟APNS Server要deviceToken。應用程式接受deviceToken。

   3、應用程式將deviceToken發送給PUSH服務端程式。

   4、 服務端程式向APNS服務發送訊息。

   5、APNS服務將訊息發送給iPhone應用程式。

    無論是iPhone用戶端跟APNS,還是Provider和APNS都需要通過認證進行串連的。下面我介紹一下幾種用到的認證。

 

(2)關於基於極光推送SDK類的封裝


  2.1  建立一個繼承於NSObject的類  ,暫時命名為  MyJPush吧

  在.h檔案中先添加幾個方法:

  /** 註冊JPush */

  +(void)registerJPush:(NSDictionary *)launchOptions;

 

  /** 添加監聽者 */

  +(void)addJPushListener:(id<CoreJPushProtocol>)listener;

 

  /** 移除監聽者 */

  +(void)removeJPushListener:(id<CoreJPushProtocol>)listener;

 

  /** 註冊alias、tags */

  +(void)setTags:(NSSet *)tags alias:(NSString *)alias resBlock:(void(^)(BOOL res, NSSet *tags,NSString *alias))resBlock;

 

  .m檔案的實現:

 

 需要宏定義一些變數:

   

  #define JPushAppKey @"***********"   //極光推送的APPKey

  #define JPushChannel @"AppStore"         //指明應用程式套件組合的下載渠道

  #define JPushIsProduction NO                 //是否是生產環境

  

  /** 註冊JPush */

  +(void)registerJPush:(NSDictionary *)launchOptions{

    

    // Required

    //可以添加自訂categories

    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |

                                                      UIUserNotificationTypeSound |

                                                      UIUserNotificationTypeAlert)

                                          categories:nil];

    

    // Required

    //如需相容舊版本的方式,請依舊使用[JPUSHService setupWithOption:launchOptions]方式初始化和同時使用pushConfig.plist檔案聲明appKey等配      置內容。

    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:JPushChannel apsForProduction:JPushIsProduction];

    

}

 

 

 

  /** 添加監聽者 */

  +(void)addJPushListener:(id<CoreJPushProtocol>)listener{

    

    MyJPush *jpush = [MyJPush sharedCoreJPush];

    

    if([jpush.listenerM containsObject:listener]) return;

    

    [jpush.listenerM addObject:listener];

}

 

 

  /** 移除監聽者 */

  +(void)removeJPushListener:(id<CoreJPushProtocol>)listener{

    

    MyJPush *jpush = [MyJPush sharedCoreJPush];

    

    if(![jpush.listenerM containsObject:listener]) return;

    

    [jpush.listenerM removeObject:listener];

}

 

 

  -(NSMutableArray *)listenerM{

    

    if(_listenerM==nil){

        _listenerM = [NSMutableArray array];

    }

    

    return _listenerM;

}

 

 

  -(void)didReceiveRemoteNotification:(NSDictionary *)userInfo{

    

    [self handleBadge:[userInfo[@"aps"][@"badge"] integerValue]];

    

    if(self.listenerM.count==0) return;

    

    [self.listenerM enumerateObjectsUsingBlock:^(id<CoreJPushProtocol> listener, NSUInteger idx, BOOL *stop) {

        

        if([listener respondsToSelector:@selector(didReceiveRemoteNotification:)]) [listener didReceiveRemoteNotification:userInfo];

    }];

}

 

 

 

  /** 處理badge */

  -(void)handleBadge:(NSInteger)badge{

    

    NSInteger now = badge-1;

    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    [UIApplication sharedApplication].applicationIconBadgeNumber=0;

    [UIApplication sharedApplication].applicationIconBadgeNumber=now;

    [JPUSHService setBadge:now];

}

 

 

 

  +(void)setTags:(NSSet *)tags alias:(NSString *)alias resBlock:(void(^)(BOOL res, NSSet *tags,NSString *alias))resBlock{

    

    MyJPush *jpush = [MyJPush sharedCoreJPush];

 

    [JPUSHService setTags:tags alias:alias callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:jpush];

    

    jpush.ResBlock=resBlock;

}

 

 

  -(void)tagsAliasCallback:(int)iResCode tags:(NSSet *)tags alias:(NSString *)alias{

 

    if(self.ResBlock != nil) self.ResBlock(iResCode==0,tags,alias);

}

 

  2.2  其次建立一個基於APPDelegate的類別檔案     暫時命名為  AppDelegate+JPush

 

  實現下列幾個方法:

  

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    

    // Required

    [JPUSHService registerDeviceToken:deviceToken];

}

 

  - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    

    // Required,For systems with less than or equal to iOS6

    [JPUSHService handleRemoteNotification:userInfo];

}

 

  - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {  

 

    // IOS 7 Support Required

    [JPUSHService handleRemoteNotification:userInfo];

    completionHandler(UIBackgroundFetchResultNewData);

    

    CoreJPush *jpush = [CoreJPush sharedCoreJPush];

    [jpush didReceiveRemoteNotification:userInfo];

}

 

這兩個檔案可以直接拿到自己的項目中使用,然後在項目中添加以下需要依賴的庫

.CFNetwork.framework

.CoreFoundation.framework

.CoreTelephony.framework

.SystemConfiguration.framework

.Security.framework

. libz.tbd

 

第二步進行項目配置:

. (1) Search Paths 下的 User Header Search Paths 和 Library Search Paths為`$(PROJECT_DIR)/CoreJPush/CoreJPush/Lib`。

. (2) 選中Project-Target-Capabilities-Background Modes,勾選Remote Notifications。

. (3) 請修改CoreJPush架構內Common檔案夾下PushConfig.plist的Appkey為您的Appkey。

. (4) 如果你的工程需要支援小於7.0的iOS系統,請到Build Settings 關閉 bitCode 選項,否則將無法正常編譯通過。

. (5)允許XCode7支援Http傳輸方法

        

        如果用的是Xcode7時,需要在App項目的plist手動加入以下key和值以支援http傳輸:

        

          <key>NSAppTransportSecurity</key> 

              <dict> 

          <key>NSAllowsArbitraryLoads</key> 

                <true/> 

            </dict>

 

最重要的一步:

   1.註冊JPush

   請刪除您的AppDelgate中所有有關推送的方法,因為CoreJPush內部已經封裝。

 

    #import "MyJPush.h"

    //註冊JPush

    [MyJPush registerJPush:launchOptions];

  

2.在您任意想得到推送資料的地方,三句代碼搞定:

 

      //1.添加一個監聽者:此監聽者是遵循了CoreJPushProtocol協議

      [MyJPush addJPushListener:self];

      

      

      //2.你需要在合適的地方(比如dealloc),移除監聽者

      [MyJPush removeJPushListener:self];

      

      

      //3.您已經遵循了MyJPushProtocol協議,直接在.m檔案裡面敲did ,Xcode會提示你如下方法:

      -(void)didReceiveRemoteNotification:(NSDictionary *)userInfo{

          NSLog(@"ViewController: %@",userInfo);

      }

 

    #pragma mark   -   在極光推送網站發送訊息,帶參數,手機接收到訊息後進行一系列操作

 

    //擷取推送的資訊(包括推送時添加的key和value,通過key擷取value的值)

    -(void)didReceiveRemoteNotification:(NSDictionary *)userInfo{

    NSLog(@"controller: %@",userInfo);

    

    if ([userInfo.allKeys containsObject :@"key"]) {           //這裡的key是自己在極光推送的平台上發送通知時自己建立的key和value

        NSLog(@"發送通知成功,開始跳轉");

        

        WebViewController *webVc = [[WebViewController alloc]init];

        

        webVc.UrlString = userInfo[@"key"];

        

        [self.navigationController pushViewController:webVc animated:YES];

        

    }

}

 

別的一些操作查看極光推送的文檔就可以了,封裝兩個檔案是為了以後配置和使用的時候更加方便,還有比較簡單的認證的配置啊什麼的就不再多說了,網上以及極光推送官網的文檔中有很明確的說明,此處需要使用的是極光推送 jpush-ios-2.1.5以後的版本

 

有需要或者指正的小夥伴可以給我留言哦!

如需源碼,可留言單獨贈送

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.