2011年9月16日

[iPhone]Push Notification機制


Push Notification機制,可以讓Server來通知有安裝軟體的device,讓有安裝app的使用者可以收到server傳來的訊息。

1.      設定Server上的Notification功能:
(1)   先到iPhone Dev Center網站選取appID並將Enable for Apple Push Notification service打勾並點選Configure,點選之後會出現產生SSL憑證的視窗。
(2)   接下來打開Mac裡面的Keychain Access程式(鑰匙圈存取),打開最上面工具列的Keychain Access(鑰匙圈存取)>Certificate Assistant(憑證輔助程式)>Request a Certificate from a Certificate Authority(從憑證授權要求憑證),填寫CA相關的資訊之後點選繼續,並選擇存放的位置之後點選完成
(3)   接下來回來原本的網頁上,點選Continue,選擇剛剛步驟(2)產生的CSR檔點選產生,等待產生完成之後,就把檔案下載回來安裝到伺服器中。

2.      Client端程式碼:

Push Notification功能的程式再啟動的時候,就會對iPhone進行Notification功能的註冊,包含了AlertBadge numberSound三種。
Alert會在iPhone上出現提示視窗,Badge number是在app icon的右上角顯示數字,Sound則是發出聲音。

我們可以在applicationFinishLauchingWithOptions:裡面加上

[[UIApplcation sharedApplication] registerForRemoteNotificationTypes :
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound];

這樣就是對Alert Badge numberSound進行註冊。

這一段code執行成功會呼叫application:didRegesterForRemoteNotificationsWithDeviceToken:
我們可以透過第二個參數得到device token,接下來要將這個device token傳給server

3.      Server傳送的格式
每一次Push Notification能夠帶payloadpayload的最大長度規定是256 bytes
並且必須帶有key”aps”dictionary

Aps dictionary
Key
Type

alert
String dictionary
可以指定要showmessage,或是傳送一個dictionary進行進階的設定
Alert dictionary
key
Type

body
string
Alert message
action-loc-key
String / null
如果指定string,原本的View button會替換成指定的string
如果指定為nullalert視窗就只會出現單一一個OK button
loc-key
string
指定顯示格式(必須儲存在Localizable.strings)
loc-args
Array of string
指定顯示字串的變數陣列
launch-image
string
指定app lunch起來的時候會顯示的畫面。

badge
Number
顯示Application icon右上角紅色的數字,傳送0,圓圈就會消失
sound
String
接收到notification的時候的聲音檔案名稱。

JSON範例
Alert message顯示Test MessageIcon右上角數字顯示3,並播放bingbiong.aiff音效。
{
  "aps":
{
 "alert":"Test Message",
"badge":3,
"sound":"bingbiong.aiff"
}
}

Alert message顯示Test Message,並播放bingbiong.aiff音效,badge不傳送則數字會消失。
{
  "aps":
{
 "alert":"Test Message",
"sound":"bingbiong.aiff"
}
}