IOS設備推送通知服務編程


-譯自 weimenglee 的Programming ApplePush Notification Services

iPhone 對於應用程序在后台運行有諸多限制(除非你越獄)。因此,當用戶切換到其他程序后,原先的程序無法保持運行狀態。對於那些需要保持持續連接狀態的應用程序(比如社區網絡應用),將不能收到實時的信息。

為解決這一限制,蘋果推出了APNs(蘋果推送通知服務)。APNs 允許設備與蘋果的推送通知服務器保持常連接狀態。當你想發送一個推送通知給某個用戶的iPhone上的應用程序時,你可以使用 APNs 發送一個推送消息給目標設備上已安裝的某個應用程序。

本文中,你將學到創建使用 APNs 的iOS 應用的詳細步驟。


創建證書請求

使用APNs 的第一步是生成一個證書請求,使用該證書請求來申請一個用於開發的 SSL 證書。

1. 打開“鑰匙串訪問”應用程序。

2. 選擇“KeychainAccess -> Certificate Assistant -> Request a Certificate From CertificateAuthority”:

3. 輸入所需的信息,勾選“Saved to disk”選項,點擊 Continue:

4. 使用默認文件名把證書請求進行保存:在彈出窗口中,點擊Done。

 

創建 App ID

每個使用 APNs 的 iOS 應用必須有一個唯一的 App ID。在本步驟中,你將學到如何創建推送通知中要用到的App ID。

1. 登錄iPhoneDeveloper Program:http://developer.apple.com/iphone/。點擊頁面右邊的“ iPhone Developer Program Portal ”:

2. 首先看到的是歡迎頁面:

3. 點擊左邊的“App ID”,然后點擊右邊的“New App ID”按鈕:

4. 在 Description 欄輸入“PushAppID”,在“Bundle Seed ID”欄中選擇“Generate New”。在“Bundle Identifier”欄,輸入“net.learn2develop.MyPushApp”,然后點擊“Submit”:

5. 現在你應該能看到所創建的 App ID 了:


配置 App

一旦創建了 App ID,你還要為推送通知對 App ID 進行一些配置。

1. 點擊App ID 右邊的 Configure 鏈接,會看到如下選項:

勾選“Enable for Apple Push Notificationservice”,點擊“Development Push SSL Certificate”右邊的“Configure”按鈕。

2. 接下來你會看到“Apple Push Notification service SSL Certificate Assistant”頁面。點擊Continue:

3. 點擊Choose File 按鈕,選擇前面保存的證書請求文件存放地址。點擊 Generate: 

4. 你的SSL 證書會被生成。點擊 Continue:

5. 點擊Download Now 按鈕,下載 SSL 證書。點擊 Done:

6. 下載的 SSL 證書文件名為 aps.developer.identity.cer。雙擊,將證書安裝到鑰匙串中。這個證書會在你的程序中用到,它允許程序接收 APNs 發送來的推送通知。

 

創建 Provisioning Profile

接下來,需要創建 provisioning profile 以便允許應用程序安裝到真實設備上。

1. 回到iPhone Development Program Portal,點擊 Provisioning 欄,點擊 New Profile 按鈕:

2. Profile Name 欄輸入 MyDevicesProfile,在 App ID 欄選擇 PushAppID。在Devices 欄,勾選所有你想激活的設備(在 iPhone Developer Program Portal 的 Devices 頁中注冊的所有設備)。點擊 Submit。

3. provisioning  profile 會等待審核。幾秒鍾后,它會顯示在頁面上。點擊Download 按鈕下載該 provisioning profile: 

4. 下載下來的provisioning profile 名為 MydevicesProfile.mobileprovision。


激活設備

創建 provision profile 后,你可以將它安裝到真實設備中。

1. 將iPhone 或 iPod 連接到 Mac。

2. 把下載下來的 MyDevicesProfile.mobileprovision 文件拖到Dock 欄的 Xcode 圖標上。

3. Xcode 的 Organizer 程序將啟動,選擇當前連機的設備。可以看到MyDevicesProfile 已自動安裝到設備上了。

 

創建 iPhone 應用程序

1. 打開Xcode,創建 View-Based Application 項目,命名為 ApplePushNotification。

2. 把一個 WAV 文件(本例是 beep.wav)拖到Xcode 的 Resouces 文件夾。

3. 展開Xcode 中的 Targets 項目,選擇ApplePushNotification,按下 ⌘+i,在 info 出口,點擊Properties 標簽欄: 

在 Identifier 文本框,輸入net.learn2develop.MyPushApp.

4. 點擊 Build 標簽欄,在 search 輸入框中鍵入Code Signing。在 Any iPhone OS Device 選項,選擇正確的 profile:

5. 在 ApplePushNotificationAppDelegate.m 文件中,輸入以下代碼(加粗部分):

 1 #import "ApplePushNotificationAppDelegate.h"
2
3 #import "ApplePushNotificationViewController.h"
4
5
6
7 @implementation ApplePushNotificationAppDelegate
8
9
10
11 @synthesize window;
12
13 @synthesize viewController;
14
15
16
17 - (void)applicationDidFinishLaunching:(UIApplication*)application {
18
19 [window addSubview:viewController.view];
20
21 [window makeKeyAndVisible];
22
23
24
25 NSLog(@"Registeringfor push notifications...");
26
27 [[UIApplication sharedApplication]
28
29 registerForRemoteNotificationTypes:
30
31 (UIRemoteNotificationTypeAlert |
32
33 UIRemoteNotificationTypeBadge |
34
35 UIRemoteNotificationTypeSound)];
36
37 }
38
39
40
41 - (void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
42
43 NSString *str = [NSString
44
45 stringWithFormat:@"Device ];
46
47 NSLog(str);
48
49 }
50
51
52
53 - (void)application:(UIApplication*)appdidFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
54
55 NSString *str = [NSStringstringWithFormat: @"Error: %@", err];
56
57 NSLog(str);
58
59
60
61 }
62
63
64
65 - (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
66
67 for (id key in userInfo) {
68
69 NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
70
71 }
72
73 }
74
75 - (void)dealloc {
76
77 [viewController release];
78
79 [window release];
80
81 [super dealloc];
82
83 }
84
85 @end

 

6. 按下 ⌘+R 運行程序(在真實設備)。按下 shift+⌘+R 顯示Debugger Console 窗口。查看設備輸出到控制台的 device token。,device token 是 38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9fe145bcc 6c2c594b。記下device token(復制、粘貼到一個文本文件里)

7. 如果查看 iPhone/iPod 上的“Settings”程序,你會發現一個 Notifications 的項:

 

創建 Push Notification Provider

Push Notification Provider 是一個應用程序,用於通過 APNs 發送推送通知給 iPhone 應用。

通過 APNs 發送推送通知有幾個步驟:
1. 使用前面創建的 SSL 證書與 APNs 通訊;

2. 構造所要發送的消息載體;

3. 發送載體到APNs;

APNs 是一個基於流的 TCP socket,你的 provider 以 SSL 協議與其通訊。推送通知(包括載體)是以二進制流的方式發送的。和APNs 建立連接后,你可以維持該連接並在連接中斷之前發送多個通知。

技巧: 應避免每發送一次推送通知就建立、關閉一次連接。頻繁的建立、關閉連接可能會被 APNs 認為是 DOS 攻擊,從而拒絕發送 provider 的推送通知發送請求。

一個推送通知消息的格式如圖24 所示:

 

更多細節,請參考 Apple Push Notification Service Programming Guide。

載體(payload)是 JSON 字符串(最長 256 字節),封裝了你發送給 iOS 應用的信息。這是一個 payload 的例子:

 1 {
2
3 "aps": {
4
5 "alert" : "Yougot a new message!" ,
6
7 "badge" : 5,
8
9 "sound" : "beep.wav"},
10
11 "acme1" : "bar",
12
13 "acme2" : 42
14
15 }



為了省去自己編寫 push notification provider 的麻煩,你可以使用 Stefan Hafeneger 寫的一個 Mac OS X 應用程序:PushMeBaby,下載地址

1. 在Xcode 中打開 PushMeBaby。

2. 右擊 Resouces 文件夾,選擇 Add Existing Files…,選擇前面所下載到的aps.developer.identity.cer 文件。

3. 在 ApplicationDelegate.m 文件中,修改如下代碼(加粗部分):

 1 - (id)init {
2
3 self = [super init];
4
5 if(self != nil) {
6
7 self.deviceToken = @"38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7ce90d56e9 fe145bcc 6c2c594b";
8
9 self.payload = @"{\"aps\":{\"alert\":\"Yougot a new message!\",\"badge\":5,\"sound\":\"beep.wav\"},\"acme1\":\"bar\",\"acme2\":42}";
10
11 self.certificate = [[NSBundle mainBundle]
12
13 pathForResource:@"aps_developer_identity" ofType:@"cer"];
14
15 }
16
17 return self;
18
19 }

 

4. 按下 ⌘+R,運行程序。將會問你是否允許使用證書,點擊Always Allow(總是允許):

 

在 iPhone/iPod,確認 ApplePushNotification 程序未運行。點擊 Push 按鈕,會向設備發送一條推送通知。服務器實際上發送了下列消息給APN 服務器:

 1 {
2
3 "aps": {
4
5 "alert" : "Yougot a new message!" ,
6
7 "badge" : 5,
8
9 "sound" : "beep.wav"},
10
11 "acme1" : "bar",
12
13 "acme2" : 42
14
15 }

 

5. 如果消息推送成功,將會在 iPhone/iPod 上出現下圖:

 

6. 如果現在按下 ⌘+R 調試 ApplePushNotification 程序,然后從 PushMeBaby 中發送一條消息,控制台會顯示如下輸出:

2009-11-24 21:11:49.182 ApplePushNotification[1461:207]key: acme1, value: bar

2009-11-24 21:11:49.187 ApplePushNotification[1461:207]key: aps, value: {

   alert = "You got a new message!";

   badge = 5;

   sound = "beep.wav";

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM