iOS 訊息推送原理及實現Demo

山天大畜發表於2013-08-06

一、訊息推送原理:

在實現訊息推送之前先提及幾個於推送相關概念,如下圖1-1

1、Provider:就是為指定IOS裝置應用程式提供Push的伺服器,(如果IOS裝置的應用程式是客戶端的話,那麼Provider可以理解為服務端[訊息的發起者]);

2、APNSApple Push Notification Service[蘋果訊息推送伺服器]

3、iPhone:用來接收APNS下發下來的訊息;

4、Client AppIOS裝置上的應用程式,用來接收iphone傳遞APNS下發的訊息到制定的一個客戶端 app[訊息的最終響應者]

上圖可以分為三個階段:

階段一:Provider[服務端]把要傳送的訊息,目的IOS裝置標識打包,傳送給APNS

階段二:APNS在自身的已註冊Push服務的IOS裝置列表中,查詢有相應標識的IOS裝置,並將訊息傳送到IOS裝置;

階段三:IOS裝置把傳送的訊息傳遞給對應的應用程式,並且按照設定彈出Push通知。

具體過程,如下圖1-2

 

1、[Client App]註冊訊息推送;

2、[Client App][APNS Service]deviceToken, Client App接收deviceToken

3、[Client App]deviceToken傳送給[Provider]Push服務端程式;

4、Push服務端程式滿足傳送訊息條件了,[Provider][APNS Service]傳送訊息;

5、[APNS Service]將訊息傳送給[Client App].

 

二、訊息推送實現:

1、生成*.certSigningRequest檔案,步驟如下:

[MacBook-應用程式-實用工具-鑰匙串訪問-證照助手-從證照機構求證照-證照資訊(使用者電子郵箱地址{填寫您的郵箱,如:your@email.com},常用名稱{任意,如:PushDemo},請求是:{單選,選擇‘儲存到磁碟’}-繼續-儲存],這時會在您指定的地方生成你指定的檔案,預設為CertificateSigningRequest.certSigningRequest檔案,這裡命名為:PushDemo.certSigningRequest.在此*.certSigningRequest已經生成,具體操作步驟如圖所示。

如果生成成功,則會在[鑰匙串訪問|登入|金鑰]欄目中列出與*.certSigningRequest關聯的金鑰,這裡是PushDemo,如圖所示:

2、新建一個App ID(在蘋果開發者賬號中配置)

(1) 登入iOS Dev Center,登入成功後,點選(iOS Provisioning Portal對應連結),如圖所示:

(2) 建立New App ID[App IDsàManageàNew App ID]( Description{填寫您對此App ID 的描述,如:iShop},Bundle Seed ID(App ID Prefix){選擇繫結App ID字首,如:預設選擇Generate New}Bundle Identifier(App ID Suffix){填寫繫結App ID字尾,如:com.yourcorp.iShop}),如下圖所示:

這樣就會生成下面這條記錄,如圖所示:

(3) 配置上一步中生成的App ID,讓其支援訊息推送[點選2-6中的Configureà選中Enable for Apple Push Notification serviceà點選Configure],如圖所示:

 (4) Generate a Certificate Signing Request(生成部署請求認證)[點選2-7中的2ConfigureàContinueà步驟1生成的*certSigningRequest檔案(這裡是iShop. certSigningRequest-Generate-生成完成後將其下載下來,命名為:aps_developer.cer],雙擊aps_developer.cer證照{將證照與金鑰關聯,並將證照匯入到MacBook},如下圖所示:

(5) 建立Development Provisioning Profiles[開發許可配置檔案]Provisioning| Development|New Profile,具體操作流程如下圖所示:

點選圖中Submit,生成Development Provisioning Profiles[開發許可配置檔案],這裡是:iShopDevprofile.mobileprovision如下圖所示:

下載此開發許可證照(用於聯機除錯)。

總結,到現在為止,我們已經生成:A*.certSigningRequest檔案(在步驟(4)中使用,用於生成證照B)B:aps_developer_identity.cer證照(在Provider[Push伺服器]服務端應用使用)、C:*..mobileprovision開發許可配置檔案(在Client App客戶端應用聯機除錯使用)。

3、新建一個專案

1. 建立一個"single view application" project,為省事,你設定的"Company Identifier" + "Production“必須和step 5建立的App ID的"bundle identifier"一致。
2. 在AppDelegate.m file的"didFinishLaunchingWithOptions" method裡,新增下列程式碼 (用於為app register push notification feature):

// Let the device know we want to receive push notifications  
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:  
 (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];  


3. 在AppDelegate.m file裡新增下列2個methods (用來handle register remote notification with device token和register error的events

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken  
{  
    NSLog(@"My token is: %@", deviceToken);  
}  
  
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error  
{  
    NSLog(@"Failed to get token, error: %@", error);  
}  
4. 執行該app in real device (simulator doesn't support push notification)。這時你會在device上看到一個popup window (該視窗只會出現一次,重灌app不會再出現),提示你該app會send push notification給你,如果同意則clickOK,不同意則click "Now allow”。如果選擇了OK,那麼在"Setting > Notifications“裡會有你的app在list裡。而且這時你的Xcode output console會顯示你的device token。

5: export "PushDemo" private key to a ".p12" file(該檔案會在後面生成apns provider的.p12 or .pem file時用到)
1). right click "PushDemo“ private key and select "Export ..."PushDemo
2). Save the private key as “PushDemoKey.p12” file, click Save button
3). 這時會讓你輸入2次用於加密該.p12 file的密碼,例如用"123321",接著會要求你輸入一次your mac account password

6: 在5中生成的“PushDemoKey.p12” file和step 6生成的"aps_development.cer" file是用於APNS provider side的原始檔,APNS Provider side進行push message時要用到的"cert + key" file就是通過這2個file來生成。該Step就是用來生成for APNS provider side (php version)要用到這個"cert + key" pem file.

1) open Terminal, go to Desktop (假設這2個file都在desktop裡)
2) 執行下列命令來生成和apns cer file對應的pem file "PushDemoCert.pem"

openssl x509 -in aps_development.cer -inform der -out PushDemoCert.pem  


3) 執行下列命令來生成和private key .p12 file對應的pem file "PushDemoKey.pem" (注意:執行過程會要求你輸入"PushDemoKey.p12"建立時設定的密碼,以及設定"PushDemoKey.pem”的密碼

openssl pkcs12 -nocerts -out PushDemoKey.pem -in PushDemoKey.p12  


4) 執行下列命令把step 11.2生成的cert pem file和step 11.3生成的key pem file合成為一個pem file  "PushDemoCK.pem"


cat PushDemoCert.pem PushDemoKey.pem > PushDemoCK.pem  

75生成的“PushDemoKey.p12” file和step 6生成的"aps_development.cer" file是用於APNS provider side的原始檔,該step是簡單測試這2個file是否有效

1) open Terminal, go to Desktop (假設這2個file都在desktop裡)

2) 執行下列命令來測試是否能夠connect apple提供的不經加密(即不需使用任何證照!)的APNS server 

telnet gateway.sandbox.push.apple.com 2195  


如果你看到下列輸出,則表示你的電腦可以connect APNS. 如果出現error,那麼check你的firewall是否允許outgoing connections on port 2195。

Trying 17.172.233.65...  
Connected to gateway.sandbox.push-apple.com.akadns.net.  
Escape character is '^]'.  
Press Ctrl+C to close the connection.


3)  執行下列命令來測試是否能夠connect apple提供的經加密(需使用2) and 3)生成的2個pem file!)的APNS "sandbox“ server for development.


openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushDemoCert.pem -key PushDemoKey.pem  


執行過程中會要你輸入PushDemoKey.pem生成時設定的密碼。如果connect server成功,就會等待你輸入字串,你可以輸入任意字串,然後回車,就會disconnect server。如果連線不成功,則openssl會顯示錯誤資訊。
注意:實際上有2個APNS servers: the “sandbox” server (用於testing) the live server(用於production mode)。我們這裡測試的是sandbox server。live apns server的操作類似。

8: 建立provider server side (php version)
1). Download SimplePush PHP code to your mac machine and then unzip it.
2). 去掉SimplePush folder裡的pk.pem (它沒用),把step 11.4生成的"PushDemoCK.pem" copy toSimplePush folder
3). 修改simplepush.php file下面幾行:
// Put your device token here (without spaces):
//device token來自Step 10的第4點,在output console獲取,注意:要去掉前後的尖括號,和中間的所有空格

$deviceToken = '43fcc3cff12965bc45bf842bf9166fa60e8240c575d0aeb0bf395fb7ff86b465';

// Put your private key's passphrase here:

//該值是 3)生成PushDemoKey.pem時設定的密碼

$passphrase = '123456';

// Put your alert message here:

$message = 'My first push notification!';

//.....stream_context_set_option($ctx, 'ssl', 'local_cert', 'PushDemoCK.pem');

4). 在terminal window裡,go to the simplepush folder,然後執行下列命令,你的iPhone應該會收到一條push message。


php simplepush.php  


注意:如果你的app在iphone裡是正在執行,而且app是在front end時,當它收到push message時是不會出現在iPhone頂部的notification area的!

 

參考文章:http://mmz06.blog.163.com/blog/static/121416962011111710934946/

     http://user.qzone.qq.com/75869071/infocenter%23!app=2&via=QZ.HashRefresh&pos=1351564081#!app=2&via=QZ.HashRefresh&pos=1351564081

相關文章