Apple Push Notification Service(APNS)的流程可以拆成三段:App 端註冊取得 deviceToken → 準備推送用的憑證 → 服務端向 APNS 下發訊息。這篇把三段都走一遍。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
return YES;
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"deviceToken: %@", deviceToken);
}
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Error in registration. Error: %@", error);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(@"收到推送消息:%@", [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"] != NULL)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"推送通知"
message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
delegate:self
cancelButtonTitle:@"關閉"
otherButtonTitles:@"更新狀態", nil];
[alert show];
[alert release];
}
}
執行後在 console 會看到類似這樣的 token:
deviceToken: <6974ac11 870e09fa 00e2238e 8cfafc7d 2052e342 182f5b57 fabca445 42b72e1b>
這串 32 位元組的資料才是 APNS 真正認得的位址。實務上通常會把它轉成 64 字元的十六字串,連同使用者識別一起回傳給自己的伺服器保存——千萬別把 token 當成使用者 ID,同一台裝置重裝 App 後 token 可能改變,舊 token 送推播時 APNS 會回報失效,該做清理。
aps_developer_identity.cer。openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
openssl pkcs12 -nocerts -out key.pem -in key.p12
# 若希望私鑰不加密碼(方便伺服器自動化使用)
openssl rsa -in key.pem -out key.unencrypted.pem
# 合併成伺服器要用的 ck.pem
cat cert.pem key.unencrypted.pem > ck.pem
提醒:去掉私鑰密碼後,ck.pem 就等於一把可直接使用的鑰匙,務必放在伺服器上權限受限的目錄,切勿進版控。
把 ck.pem 與下列腳本放到伺服器:
<?php
$deviceToken = '6974ac11 870e09fa 00e2238e 8cfafc7d 2052e342 182f5b57 fabca445 42b72e1b';
$pass = '123456'; // ck.pem 的 passphrase
// 參數可來自 HTTP GET 或命令列
$message = $_GET['message'] or $message = $argv[1] or $message = 'A test message';
$badge = (int)$_GET['badge'] or $badge = (int)$argv[2];
$sound = $_GET['sound'] or $sound = $argv[3];
// 組裝 payload
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge) $body['aps']['badge'] = $badge;
if ($sound) $body['aps']['sound'] = $sound;
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
// 連線 APNS(sandbox 位址)
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195',
$err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect $err $errstr\n";
return;
} else {
print "Connection OK\n<br/>";
}
// 依 APNS 的二進位封包格式送出
$payload = json_encode($body);
$msg = chr(0) . pack("n", 32) . pack('H*', str_replace(' ', '', $deviceToken))
. pack("n", strlen($payload)) . $payload;
print "Sending message :" . $payload . "\n";
fwrite($fp, $msg);
fclose($fp);
?>
請求 https://127.0.0.1/apns/apns.php?message=A%20test%20message&badge=2&sound=received5.caf 即會推送一次,輸出如下:
Connection OK
Sending message :{"aps":{"alert":"A test message","badge":2,"sound":"received5.caf"}}
另一種做法是使用 pushMeBaby 這類現成工具,把 aps_developer_identity.cer 匯入專案並改名為 apns.cer,就能透過圖形介面測試。
務必分清 gateway.sandbox.push.apple.com(開發)與 gateway.push.apple.com(正式)兩個位址,憑證也不通用,這是新手最常見的「推不出來」原因。此外,payload 有大小上限(當時為 256 位元組),過長會被 APNS 直接丟棄;連線盡量重複使用而非每次推送都重建,並記得定期讀取 APNS 的 feedback 服務來清理失效 token。
上述程式碼屬於舊版 API 寫法,在現行 iOS 上應改用 UIRegisterForRemoteNotifications 搭配 UNUserNotificationCenter,服務端也建議使用 HTTP/2 的 provider API;但整體流程——註冊、拿 token、備憑證、下發——至今未變。