Registering for Remote Push Notifications

Local Notifications 和 Push Notifications 是兩種方式讓 iOS Application 在沒有執行的時候可以讓使用者得知訊息。使用情境上這個通知可以是訊息、一個行事曆事件或者遠端伺服器的新資料。而通知可以以 Alert 訊息或者是 Badge 數字來呈現。也可以當在 Alert 或者 badge 數字顯示時候播放聲音。

Push notifications 在  iOS 3.0 即有此功能,而 local notifications 在 iOS 4.0 才有。

先前我紀錄過 Local Notifications let users know it has something for them 如何進行,本篇則是以 iOS push notification 規劃上 client app 開發上步驟與事項為主。

要完成 Push Notifications 必須要三方的合作,分為 Push Provider、Apple push notification service、iPhone app。

iOS app for iPod/ iPhone/ iPad 必須要跟 Apple Push Notification service 註冊,如此 iOS 才能接收到 Application's provider 從遠端發佈訊息。而註冊對於 iOS app 而言分為三個步驟。

1. 呼叫 UIApplication 的 registerForRemoteNotificationTypes: method
2. 在 UIApplicationDelegate 實作 application:didRegisterForRemoteNotificationsWithDeviceToken: 來接收 device token。
3. 把 device token 非物件而是 binary 值這樣資料傳送給 Provider。

這些溝通過程在 Apple 上有個 Token Generation and Dispersal 文件可以參考整個流程。我們要注意的是,iOS application 必須每次在啟動時候要跟 Apple 註冊,取得最新版的 device token 寄給 provider。呼叫 registerForRemoteNotificationTypes: 來取得最新 device token,而這邊的類型接收 UIRemoteNotificationType,透過這邊來決定要索取通知時候支援哪些形式,Alert、badge number、sound。

如果註冊成功,APNs 會回傳 device token 到該台裝置上,透過 application delegate 進入 application:didRegisterForRemoteNotificationsWithDeviceToken:  這 method 裡面。而接下來就把這資料傳給 provider。

如果註冊失敗,APNs 會回傳到該台裝置上 application delegate 的 application:didFailToRegisterForRemoteNotificationsWithError: method ,藉由 NSError 物件來明白說明發生了怎麼樣的狀況。大部份會碰到問題是環境設定有關,所以要參考 “Creating and Installing the Provisioning Profile” 可以取得更多細節。

每次 Application 重新啓動都要將最新版的 device token 傳給 provider 這樣才能協助確保掌握擁有最新該台有效 token。如果今天使用者擁有多台裝置,備份還原,那麼到了新的裝置上也必須執行一次來取得 notification。所以記得不要將 device token cache 起來才交給 provider,記得要取得最新的。

註冊遠端 notification。

成功接受到 device token 會長這樣內容 <baf649a9 bc942e91 3981a908 c623620a 571f260a ee573919 82abe637 adw39a4e>

失敗時候,例如用 iOS 開發模擬器會得到『該裝置不支援遠端通知的服務』。
當我們將 Device token 訊息傳給 provider,接下來就是等接收了。iOS app 可以接收到遠端通知的入口是在 UIApplication 的 application:didReceiveRemoteNotification: 這個 method,而 user info 則是傳入一則 JSON 的 message,可以再此解開來,做該 iOS 要運作的邏輯。格式類似   { "aps" : { "alert" : "某某超商有新活動" }, "content" : 33, "type" : "AS5" } 為例,在 APS 裡面的 key/value  可以自行定義。而 iOS app 再根據這樣的事件觸發後,導到想要顯示的 iOS 頁面 view controller 即可讓使用者知道最新活動消息。

以上為 Push notification 在開發實作上比較複雜,牽扯到 Push provider 和 iOS app 的實作,本篇以後者 iOS app 開發上要注意部份。

Comments