iOS 的推送機制可以濃縮成一張流程圖:

其中 Provider 是你自己架設的推送伺服器,APNS 則是 Apple Push Notification Service,蘋果的推送服務。
第一階段:App(Provider)把要發送的消息與目標 iPhone 的標識打包,送給 APNS。
第二階段:APNS 在已註冊的裝置清單中查找該標識對應的 iPhone,把消息送達。
第三階段:iPhone 把消息傳給對應的 App,App 依設定彈出通知。

無論是 iPhone ↔ APNS,還是 Provider ↔ APNS,兩端都需要憑證才能建立連線。
第一步是產生 Certificate Signing Request。

在鑰匙圈存取(Keychain Access)選單中選擇「憑證助理 → 從憑證機構請求憑證」。

填入你的電子郵件與常用名稱,並選擇「儲存到磁碟」。

完成後本地會產生一個 Push.certSigningRequest 檔。
接著在鑰匙圈存取中把自己的憑證與私鑰一起匯出。


設定一組匯出密碼。

如此就得到 Push.p12 檔。這個檔包含私鑰,是推送伺服器連線 APNS 的必要材料,務必妥善保管、不要進版控。
用付費開發者帳號登入 iOS Provisioning Portal,新增一個 App ID。

點擊右側的 Configure。

找到 Development Push SSL Certificate 一列,點擊 Configure。

點擊 Continue。

選擇前面產生的 Push.certSigningRequest,點擊 Generate。

點擊 Continue。

點擊 Download,把檔案命名為 aps_developer_identity.cer。
點擊 Done 後,你會看到狀態變成 Enabled。

注意:某些 App ID 的 Apple Push Notification service 欄位是灰色的、無法點擊 Configure,這是因為 APNS 不支援帶萬用字元的 App ID。
在 AppDelegate 的 didFinishLaunchingWithOptions 中註冊:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
這行程式碼告訴系統:本 App 能接受推送通知。
接著實作取得 token 的回呼:
- (void)application:(UIApplication *)app
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
NSLog(@"My token is: %@", token);
}
- (void)application:(UIApplication *)app
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSString *error_str = [NSString stringWithFormat:@"%@", error];
NSLog(@"Failed to get token, error: %@", error_str);
}
取到的 deviceToken 要提交給後台伺服器。後台要發送通知時,除了需要 deviceToken,還需要一份能與 APNS 建立連線的憑證——也就是前面產生的那兩個檔案。
先把 cer 轉成 pem 格式:
openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem -outform PEM
再把 p12 格式的私鑰轉成 pem:
openssl pkcs12 -nocerts -out Push_Noenc.pem -in Push.p12
最後合併產出 p12 檔:
openssl pkcs12 -export -in aps_developer_identity.pem -inkey Push_Noenc.pem -certfile Push.certSigningRequest -name "aps_developer_identity" -out aps_developer_identity.p12
這樣就得到可在 .NET 或 Java 後台程式中使用的 aps_developer_identity.p12。若後台是 PHP,則可另參照 pem 檔的產生方式,產出 ck.pem。
%@ 直接印出 NSData 只是除錯用,正式上報時應轉為 64 個十六進位字元組成的字串。