直接進入主題。在動手之前,先把整個推送流程的關鍵環節列出來:
整體流程圖如下:

幾個角色先釐清:
App 必須先向 APNS 註冊才能獲得推送能力。註冊成功後,APNS 會回傳一個裝置標識符即 DeviceToken,服務端在發送通知時必須指定目標裝置的 DeviceToken。
iOS 8 之後,註冊流程分為四步:
registerUserNotificationSettings: 註冊 App 想支援的通知類型(提示框、角標、聲音)registerForRemoteNotifications 向 APNS 註冊第一個 API 是 iOS 8 新增的,因此在 iOS 7 上要用舊寫法。另外請注意:DeviceToken 有可能變動,所以每次啟動都應該重新註冊並上傳,不要只在首次安裝時做一次。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// iOS 8 以上
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound
categories:nil];
[UIApplication.sharedApplication registerUserNotificationSettings:settings];
} else {
// iOS 7 及更早
[UIApplication.sharedApplication registerForRemoteNotificationTypes:
UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
}
return YES;
}
// 使用者授權完成後,才真正向 APNS 註冊
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings *)settings {
[application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token {
NSLog(@"註冊成功,bundle id: %@, mode: %@, token: %@",
[NSBundle.mainBundle bundleIdentifier], [self modeString], token);
// 這裡把 token 上傳到伺服器
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"註冊失敗: %@", error);
}
// iOS 8:使用者透過通知的動作按鈕回應時
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)notification
completionHandler:(void(^)())completionHandler {
NSLog(@"收到推送: %@, identifier: %@", notification, identifier);
completionHandler();
}
// iOS 7 及更早
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)notification {
NSLog(@"收到推送: %@", notification);
}
- (NSString *)modeString {
#if DEBUG
return @"Development (sandbox)";
#else
return @"Production";
#endif
}
(1)App 未啟動時收到通知,訊息內容會透過 didFinishLaunchingWithOptions 的 launchOptions 傳入:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (payload) {
// 在此處理,例如直接跳轉到對應頁面
}
return YES;
}
(2)App 在前景執行時,收到通知預設不會有任何提示(無提示框、無橫幅)。在背景時會有系統提示,使用者點擊後進入 App,didReceiveRemoteNotification 被呼叫:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)payload {
NSLog(@"remote notification: %@", [payload description]);
NSDictionary *apsInfo = [payload objectForKey:@"aps"];
NSObject *alert = [apsInfo objectForKey:@"alert"];
NSString *alertStr = nil;
if ([alert isKindOfClass:[NSString class]]) {
alertStr = (NSString *)alert;
} else if ([alert isKindOfClass:[NSDictionary class]]) {
alertStr = [(NSDictionary *)alert objectForKey:@"body"];
}
application.applicationIconBadgeNumber = [[apsInfo objectForKey:@"badge"] integerValue];
// 僅在前景時才自行彈出提示,背景時交由系統處理
if ([application applicationState] == UIApplicationStateActive && alertStr != nil) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Pushed Message"
message:alertStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
}
可以把自訂音效檔放進 App bundle,收到通知時指定播放。檔案必須屬於以下格式之一:
可打包為 aiff、wav 或 caf。時長必須少於 30 秒,超過則會被系統音取代。
Payload 是每條推送通知的核心,它決定系統如何提醒使用者,也可攜帶自訂資料。Payload 本身是 JSON 字串,內部必須包含一個名為 aps 的字典,其中可含以下欄位:
若要攜帶自訂欄位,請與 aps 同層加入即可:
{
"aps" : {
"alert" : "This is the alert text",
"badge" : 1,
"sound" : "default"
},
"server" : {
"serverId" : 1,
"name" : "Server name"
}
}
如此一來,用戶端收到的 payload 中就會多出一個 server 欄位。
一般後端服務會需要你提供推送憑證與對應私鑰導出的 p12 檔,而 APNS 溝通時需要的是 pem 格式,因此需要自行轉換。
準備工作:
第三步是很多人踩過的坑:一個 App 的推送憑證不一定與根憑證來自同一台電腦,也就是產生的 certSigningRequest 不同,私鑰自然也不同。轉 pem 時務必使用推送憑證自己的私鑰,否則連線會直接被 APNS 拒絕。
操作步驟:
# A. 憑證 .cer 轉 .pem openssl x509 -in 推送憑證.cer -inform der -out 推送憑證.pem # B. 私鑰 .p12 轉 .pem openssl pkcs12 -nocerts -out 推送憑證私鑰.pem -in 推送憑證私鑰.p12 # C. 把憑證與私鑰合併成一個檔案 cat 推送憑證.pem 推送憑證私鑰.pem > PHPPush.pem
把 PHPPush.pem 交給後端同事即可。
測試推送往往需要後端配合,但溝通成本不低。其實自己就能推,不必麻煩別人。以下 PHP 腳本可完成一次完整推送:
<?php
// 目標裝置的 deviceToken
$deviceToken = '你的deviceToken';
// 建立 pem 時設定的私鑰密碼
$passphrase = '123456';
// 自訂推送內容
$message = array('body' => '你收到一個新訂單');
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => 100,
);
$body['type'] = 3;
$body['msg_type'] = 4;
$body['title'] = '新訂單提醒';
$body['msg'] = '你收到一個新訊息';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'push.pem'); // 與本檔案同一目錄
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// 開發環境走 sandbox,正式環境走 gateway,兩者的 deviceToken 並不通用
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', // 'ssl://gateway.push.apple.com:2195',
$err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) echo 'Message not delivered' . PHP_EOL;
else echo 'Message successfully delivered' . PHP_EOL;
fclose($fp);
?>
將其存為 push.php,依前述步驟產生 push.pem,兩個檔案放在同一目錄後執行:
$ php push.php
成功時輸出:
Connected to APNS Message successfully delivered
最後提醒兩件容易忽略的事:一是憑證環境必須與 token 來源一致,開發版描述檔產生的 token 只能用 sandbox 位址推送,換到正式位址會直接連線失敗;二是角標數字要用絕對值而非增量,APNS 不會幫你累加,伺服器必須自行維護每位使用者的未讀計數。
以上就是 iOS 推送的整體輪廓,希望對大家的學習有所幫助。