iOS 消息推送的工作機制可以簡單地用下圖概括:應用先向系統註冊通知權限,系統回傳 deviceToken,再把 token 提交給後台伺服器;後台伺服器搭配與 APNS 連線的證書,即可將通知推送給指定裝置。
首先,透過 registerForRemoteNotificationTypes 方法告訴應用程式它能接收推送通知:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
接著在 AppDelegate 中實作以下方法來取得 deviceToken:
- (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 連線的證書,這個證書可從前面產生的檔案轉換而來。
1. 將 aps_developer_identity.cer 轉換成 aps_developer_identity.pem 格式:
openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem -outform PEM
2. 將 p12 格式的私鑰轉換成 pem:
openssl pkcs12 -nocerts -out Push_Noenc.pem -in Push.p12
3. 建立 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,則可依相關教學產生 PHP 後台使用的 ck.pem 憑證檔案。