2015年1月23日 星期五

iOS APNS - Apple Push Notification Service (訊息推播)簡介

APNS 介紹
APNS 為 Apple Push Notification Service的縮寫,也就是大家常說的 Push Notification,簡單說就是主動由 Server 發送訊息到 Client 的方法。目前市面上最普及的手機作業系統為Android及iOS,APNS就是iOS上的Push Notification技術。

在 iOS 所提供的 APNS 的架構中,包含了以下幾種角色:

  • Device - 行動上網裝置,即iPhone、iPad
  • APNS - Apple 提供連線服務的伺服器 (Gateway)
  • Provider - 需要自行實作的訊息發送者,也就是負責與APNS溝通的Server端
圖片來源:iOS Developer Library

由上圖可知,Provider發送請求至APNs,APNs收到請求後依據請求中的描述,將Notification發送到手機(或平板)。

The Notification Payload Block

Provider 通知APNs發送訊息時,必須傳送一個固定格式的資料到 APNS,這個資料我們稱為 Payload。Payload 使用 JSON 格式進行定義,alert 提供文字訊息顯示;badge 提供 App 圖示右上角的顯示數字;sound 則提供收到訊息要播放的聲音(可在 App Bundle 自行定義)。除了這些功能,Payload 還允許我們自己定義要傳送的資料,Payload 格式如下:

{    
  "aps": {
        "alert": "Hello World.",
        "badge": 9,
        "sound": "default"
    },
    "custom_key": "custom_value"
}