iOS客戶端的APNS服務簡介與實現

APNs --Apple Push Notification Service
APNs ×××送服務器
Device 安裝帶有推送服務程序的iPhone手機
Provider 程序服務器,把須要推送的信息發給 APNs
DeviceToken 在Device第一次鏈接APNs時,由APNs生成的通過加密的鏈接認證信息。在之後的鏈接中,不管時Provider到APNs仍是APNs到Device 都須要 DeviceToken做爲認證。
Payload 須要推送的消息的主體內容。alert-alert消息的消息體,按鍵標題等badge-顯示在程序icon右上角的數字,sound-聲音提示文件的文件名,該聲音資源文件要在程序包中。
總體流程大致分爲五個步驟:
1:  Device --> 鏈接-->  APNs  獲取 DeviceToken
2:  Device -->鏈接-- > Provider 提供 DeviceToken


3:  Provider偵測須要push的消息生成Notification信息

4:  Provider偵把要push的消息推送到APNs
5:  APNs把該消息推送到手機
 

介紹完APNS的概況,下面再瞭解一下具體的實現方法:
注:先申請APNS的證書,再進行如下操做。

1. 將app註冊notification裏面, 並從APNS上獲取測試機的deviceToken.
 
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  2.    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
  3.        // other codes here.
  4.    return YES;
  5. }
  6.  
  7. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  8.    NSLog(@」deviceToken: %@」, deviceToken);
  9. }
  10.  
  11. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  12.    NSLog(@」Error in registration. Error: %@」, error);
  13. }
  14.  
  15. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
  16. {
  17.    NSLog(@」 收到推送消息 : %@」,[[userInfo objectForKey:@"aps"] objectForKey:@」alert」]);
  18.    if ([[userInfo objectForKey:@"aps"] objectForKey:@」alert」]!=NULL) {
  19.        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@」推送通知」
  20.                                                        message:[[userInfo objectForKey:@"aps"] objectForKey:@」alert」]
  21.                                                       delegate:self
  22.                                              cancelButtonTitle:@」 關閉」
  23.                                              otherButtonTitles:@」 更新狀態」,nil];
  24.        [alert show];
  25.        [alert release];
  26.    }
  27. }
 
啓動程序,將app註冊到通知項後,在console裏面找到打印的deviceToken:
 
  1. deviceToken: <6974ac11 870e09fa 00e2238e 8cfafc7d 2052e342 182f5b57 fabca445 42b72e1b>
 
2. 生成app在服務端須要的許可證
1)進入Provisioning Portal, 下載Certificates在development下的證書。
2) 找到須要測試的app id,而後enable它在development下的Apple Push Notification service: Development Push SSL Certificate。須要輸入1)中的簽名證書才能夠生成一個aps_developer_identity.cer.
3) 雙擊aps_developer_identity.cer,會打開系統的key chain. 在My certificates下找到Apple Development Push Services。須要爲certificate和它之下的private key各自export出一個.p12文件。(會出現設置密碼過程)
4)須要將上面的2個.p12文件轉成.pem格式:
 
  1. openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
 
 
 
  1. openssl pkcs12 -nocerts -out key.pem -in key.p12
 
5)若是須要對 key不進行加密:
 
  1. openssl rsa -in key.pem -out key.unencrypted.pem
 
6)而後就能夠 合併兩個.pem文件, 這個ck.pem就是服務端須要的證書了。
 
  1. cat cert.pem key.unencrypted.pem > ck.pem
 
3. 服務端push通知到ANPS. 在cocoachina找到了兩種方法:
1)php驅動。須要將ck.pem和php腳本放到server 上。所有的php代碼是:
 
  1. <?php
  2. $deviceToken = ’6974ac11 870e09fa 00e2238e 8cfafc7d 2052e342 182f5b57 fabca445 42b72e1b’;
  3. $pass = ’123456′;   // Passphrase for the private key (ck.pem file)
  4.  
  5. // Get the parameters from http get or from command line
  6. $message = $_GET['message'] or $message = $argv[1] or $message = ‘A test message from worldcup’;
  7. $badge = (int)$_GET['badge'] or $badge = (int)$argv[2];
  8. $sound = $_GET['sound'] or $sound = $argv[3];
  9.  
  10. // Construct the notification payload
  11. $body = array();
  12. $body['aps'] = array(‘alert’ => $message);
  13. if ($badge)
  14.  $body['aps']['badge'] = $badge;
  15. if ($sound)
  16.  $body['aps']['sound'] = $sound;
  17.  
  18. /* End of Configurable Items */
  19. $ctx = stream_context_create();
  20. stream_context_set_option($ctx, ‘ssl’, ‘local_cert’, ‘ck.pem’);
  21. // assume the private key passphase was removed.
  22. stream_context_set_option($ctx, ‘ssl’, ‘passphrase’, $pass);
  23.  
  24. // connect to apns
  25. $fp = stream_socket_client(‘ssl://gateway.sandbox.push.apple.com:2195′, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
  26. if (!$fp) {
  27.    print 「Failed to connect $err $errstr\n」;
  28.    return;
  29. }
  30. else {
  31.   print 「Connection OK\n<br/>」;
  32. }
  33.  
  34. // send message
  35. $payload = json_encode($body);
  36. $msg = chr(0) . pack(「n」,32) . pack(‘H*’, str_replace(‘ ‘, 」, $deviceToken)) . pack(「n」,strlen($payload)) . $payload;
  37. print 「Sending message :」 . $payload . 「\n」;
  38. fwrite($fp, $msg);
  39. fclose($fp);
  40. ?>
 
請 求一次 http://127.0.0.1/apns /apns.php?message=A%20test%20message%20from%20localhost&badge=2& sound=received5.caf就 會向APNS進行一次推送。個人請求結果以下:
 
  1. Connection OK
                2. Sending message :{「aps」:{「alert」:」A test message from localhost」,」badge」:2,」sound」:」received5.caf」}}
轉自 iOS分享網 http://iosshare.cn