訊息推送之APNS,訊息推apns

來源:互聯網
上載者:User

訊息推送之APNS,訊息推apns

利用APNS進行訊息推送

原理

APNS 是Apple Push Notification Service(Apple Push伺服器)的縮寫,是蘋果的伺服器。

APNS推送可以分為三個階段:

第一階段:推送伺服器應用程式把要發送的訊息、目的iPhone的標識打包,發給APNS。

第二階段:APNS在自身的登入推送服務的iPhone列表中,尋找有相應標識的iPhone,並把訊息發到iPhone。

第三階段:iPhone把發來的訊息傳遞給相應的應用程式,並且按照設定彈出推播通知。

詳細流程如下:

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

2、APNS嚮應用程式返回deviceToken。

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

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

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

 

認證產生

網上有很多關於認證產生的詳細步驟,這裡不再說明了。

最終產生的認證共包含下面四個

1、pushNotification.certSigningRequest

2、aps_development.cer(下載產生的支援推送服務的認證。)

3、pushNotificationDevprofile.mobileprovision

4、pushNotification.p12

 

下面直接上代碼。

 

用戶端

1、應用程式註冊訊息推送服務

在AppDelegate.m的(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中加入註冊訊息通知推送服務。

1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions2 {3   //判斷是否由遠程訊息通知觸發應用程式啟動4     if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]!=nil) {5         NSLog(@"遠程訊息通知觸發應用程式啟動");6     }7     //訊息推送註冊8     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge];9 }

 

2、接收deviceToken的方法

在項目的AppDelegate.m中加入以下兩個代理方法

1 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 2     NSString *token = [NSString stringWithFormat:@"%@", deviceToken]; 3     //擷取終端裝置標識,標識擷取後需要將其發送到伺服器端,伺服器端推送訊息到APNS時需要知道終端的標識,APNS通過註冊的終端標識找到終端裝置。4     NSLog(@"My token is:%@", token);   5 }  6 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {   7     NSString *error_str = [NSString stringWithFormat: @"%@", error];   8     NSLog(@"Failed to get token, error:%@", error_str);   9 } 

 

3、接收訊息的處理方法

在項目AppDelegate.m中加入訊息接收處理代理方法。

1 - (void)application:(UIApplication *)application 2 didReceiveRemoteNotification:(NSDictionary *)userInfo3 {4     //在此處理接收到的訊息。5     NSLog(@"Receive remote notification : %@",userInfo);6 }

 

至此,IOS端的代碼已經碼完了。(^_^)

 

 

伺服器

伺服器端可以用php、Java、.net等語言實現。本文使用Java語言實現

1、匯入jar包

工程建好之後,將JavaPNS_2.2.jar、javapns-jdk16-163.jar、bcprov-jdk16-145.jar這幾個jar包拷貝到工程的lib目錄下。

2、產生伺服器端所用的.p12檔案(.net或Java等後台)

在mac終端下執行以下指令:

(1)、將aps_development.cer轉換成aps_development.pem格式

$ openssl x509 -in aps_development.cer -inform DER -out aps_development.pem -outform PEM  

(2)、將p12格式的私密金鑰轉換成pem

$ openssl pkcs12 -nocerts -out Push_Noenc.pem -in pushNotification.p12  

(3)、建立p12檔案

$ openssl pkcs12 -export -in aps_development.pem -inkey Push_Noenc.pem -certfile pushNotification.certSigningRequest -name "aps_development" -out aps_development.p12  

這樣我們就得到了在.net或java等後台應用程式中使用的認證檔案:aps_development.p12

3、編寫伺服器端代碼

  1 package com.push.server;  2 import java.io.FileInputStream;  3 import java.io.FileNotFoundException;  4 import java.io.IOException;  5 import java.util.ArrayList;  6 import java.util.List;  7 import java.util.Properties;  8   9 import javapns.devices.Device; 10 import javapns.devices.implementations.basic.BasicDevice; 11 import javapns.notification.AppleNotificationServerBasicImpl; 12 import javapns.notification.PushNotificationManager; 13 import javapns.notification.PushNotificationPayload; 14 import javapns.notification.PushedNotification; 15  16 public class SendToAPNS { 17     // 從用戶端擷取的deviceToken,在此為了測試,設一個固定值 18     private static final String DEVICE_TOKEN =  19  20 "13b11050a3fc064b3692e25c0fbd3b774b39ecb0c55a51ff4fb1373e004577a0"; 21     List<String> deviceToken = new ArrayList<String>(); 22      23     public void send () { 24         // 認證檔案(.p12)在伺服器端的目錄 25         String filePath = null; 26         try { 27             String path = this.getClass().getClassLoader().getResource("/").getPath(); 28             filePath = java.net.URLDecoder.decode(path,"utf-8"); 29         } catch (Exception e){ 30             e.printStackTrace(); 31         } 32         System.out.println("filePath=" + filePath); 33         String certificatePath = (filePath + "conf/ios_development.p12"); 34         // 擷取ios_development.p12的密碼 35         Properties prop = new Properties();   36         FileInputStream fis = null; 37         try { 38             fis = new FileInputStream(filePath + "conf/pushmessage.properties"); 39               40         } catch (FileNotFoundException e) { 41             // TODO Auto-generated catch block 42             e.printStackTrace(); 43         }   44         try { 45             prop.load(fis); 46         } catch (IOException e) { 47             // TODO Auto-generated catch block 48             e.printStackTrace(); 49         } 50         String certificatePassword = prop.getProperty("password");   51          52         // 構建發送的訊息 53         String message="{'aps':{'alert':'this is a push message'}}"; 54          55         // 設別標識 56         deviceToken.add(DEVICE_TOKEN); 57         // 發送訊息 58         sendpush(deviceToken, certificatePath, certificatePassword, message, 4, false); 59     } 60      61      /************************************************ 62      測試用URL gateway.sandbox.push.apple.com /2195  63      正式發布用URL gateway.push.apple.com / 2195  64     javaPNS_2.2.jar必須 65      ***************************************************/ 66     /** 67    * @param tokens   iphone裝置的唯一標識 68  69    * @param path   .p12認證檔案的路徑 70  71    * @param password  .p12認證檔案的密碼 72  73    * @param message   發送的訊息內容 74  75    * @param count 76  77    * @param sendCount  true 一對一發送      false 群發 78  79    */ 80     public void sendpush(List<String> tokens,String path, String password, String message,Integer  81  82 count,boolean sendCount) { 83         try { 84             // message:{"aps":{"alert":"一條新訊息"}} 85             PushNotificationPayload payLoad =  PushNotificationPayload.fromJSON(message); 86             //payLoad.addAlert(message); 87             payLoad.addBadge(count); 88             payLoad.addSound("default"); 89              90             PushNotificationManager pushManager = new PushNotificationManager(); 91             // true 正式發布用URL 92             // false 測試用URL 93             pushManager.initializeConnection(new AppleNotificationServerBasicImpl(path, password,  94  95 false)); 96             List<PushedNotification> notifications = new ArrayList<PushedNotification>();  97             // 推送方式 98             if (sendCount) { 99                 System.out.println("-------現在進行一對一推送-------");100                 Device device = new BasicDevice();101                 device.setToken(tokens.get(0));102                 PushedNotification notification = pushManager.sendNotification(device, payLoad, 103 104 true);105                 notifications.add(notification);106             } else {107                 System.out.println("------現在進行群發-------");108                 List<Device> device = new ArrayList<Device>();109                 for (String token : tokens) {110                     device.add(new BasicDevice(token));111                 }112                 notifications = pushManager.sendNotifications(payLoad, device);113             }114 115             List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications116 117 (notifications);118             List<PushedNotification> successfulNotifications = 119 120 PushedNotification.findSuccessfulNotifications(notifications);121             int failed = failedNotifications.size();122             int successful = successfulNotifications.size();123             124             if (successful > 0 && failed == 0) {125                 //log.debug("-----All notifications pushed success (" + 126 127 successfulNotifications.size() + "):");128                 System.out.println("-----All notifications pushed success (" + 129 130 successfulNotifications.size() + "):");131             } 132             else if (successful == 0 && failed > 0) {133                 //log.debug("-----All notifications pushed failed(" + failedNotifications.size() + 134 135 "):");136                 System.out.println("-----All notifications pushed failed(" + 137 138 failedNotifications.size() + "):");139             } 140             else if (successful == 0 && failed == 0) {141                 System.out.println("No notifications could be sent, probably because of a critical 142 143 error");144             } 145             else {146                 //log.debug("------Some notifications pushed failed (" + failedNotifications.size147 148 () + "):");149                 //log.debug("------Others pushed success(" + successfulNotifications.size() + 150 151 "):");152                 System.out.println("------Some notifications pushed failed (" + 153 154 failedNotifications.size() + "):");155                 System.out.println("------Others pushed success(" + successfulNotifications.size() 156 157 + "):");158             }159             pushManager.stopConnection();160             161         } catch (Exception e) {162             e.printStackTrace();163         }164     }165 }

 

 至此,伺服器端代碼也碼完了。(^_^)

 

APNS推送的特點

從APNS的文檔中大概總結了以下幾點:

1、提供單一發送和群發功能。

2、當使用者手機不線上(可能沒有訊號或者關機),APNs會儲存轉寄,等使用者線上時再發送。

3、如果使用者長時間不線上,這條資訊會被忽略。

4、如果使用者不線上,通知會合并,只會保留最新的一條。

5、payload,就是最後產生的那段Json,不得超過256位元組。如果超過了,建議去掉一些不需要的參數,把alert,就是提示

資訊的字數減少。

6、發送成功的沒有返回,只有發送失敗的才會返回。

7、如果有error-response,那麼這條之後的通知都需要重發。

8、如果出錯了,需要關閉當前的串連,並且重新串連再發。error-response中返回的通知ID,可以協助我們找出哪條出錯

了,這樣就能知道哪些需要重發了。

9、不要反覆多次串連、終止與APNS的串連,否則會被APNS拒絕串連。

10、APNS的feedback service會返回那些已經卸載的裝置的deviceToken。對於這些token,下次就不用再發了。可以節省

點資源。需要注意的是:feedback的介面讀取一次,APNS就會清空它的列表,下次再讀取時,返回的就是這兩次讀取之間這

段時間新產生的deviceToken

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.