推送通知(又稱遠程通知)是 iOS 3.0 之後引入的功能,用途是在 App 未啟動或不在前台運行時,通知使用者有新消息。它從外部伺服器發送,路徑是:你的伺服器 → 蘋果推送通知服務(Apple Push Notification service,APNs)→ 使用者裝置上的 App。
通知內容可以是一則訊息、一項即將到期的提醒,或提示遠端有新資料。呈現形式包括橫幅警告、App 圖示上的數字角標,以及提示音。使用者可以點擊進入 App 處理,也可以忽略,此時 App 不會被啟動。
由於 iPhone、iPad、iPod touch 同一時刻只有一個 App 在前台,多數程式在背景時無法主動告知使用者發生了什麼事。推送通知正是為了解決這個問題。
1. 訊息推送:提供者(Provider,即你的伺服器)透過串流式 TCP socket,把通知以二進位格式送給 APNs。APNs 有兩個入口,各自有獨立的位址與埠,且都必須透過 TLS/SSL 建立加密通道:
2. 回饋服務(Feedback Service):可查詢某個 App 的推送失敗記錄。提供者應週期性呼叫它,找出那些已持續無法收到通知的裝置(例如使用者刪了 App 或關閉了通知權限),停止對它們發送,以降低伺服器負擔:
要開發與部署推送,必須透過 iOS Developer Program 取得 SSL 憑證。每張憑證只綁定一個 App(以 bundle ID 識別),且分為沙盒與正式兩種用途,兩種環境也需要各自的 provisioning profile。
整體流程可以拆成五步:
其中 Provider 是你自己要開發的伺服器端程式,APNs 則是蘋果的服務。整個過程可歸為三階段:Provider 把「訊息 + 目標裝置標識」打包送給 APNs;APNs 在已註冊的裝置清單中查找並投遞;裝置收到後交給對應 App,依設定彈出通知。
在 iOS 開發團隊中有三種角色:Team Manager、Team Admin、Team Member。開發憑證與配置文件的建立權限依角色而定:通常只有 Team Manager 能建立 Development SSL 憑證(沙盒)與 Distribution SSL 憑證(正式);Manager 與 Admin 都能建立 Development 與 Distribution 的 provisioning profile;Member 則只能下載安裝。
這裡要先釐清兩個常被混淆的概念:憑證(Certificates)是以鑰匙圈產生的簽名密鑰;配置文件(Provisioning Profiles)則是針對特定 App 產生的簽名設定檔,內容包含憑證、裝置 UDID、bundle ID 與權利(entitlements)。一個開發者帳號通常只有一支 Development 憑證與一支 Distribution 憑證,但可以有非常多個 profile,且這些 profile 往往共用同一張憑證。
回到 Portal 的 Configure App ID 頁面,狀態會變綠並顯示 Enabled。若要為正式環境建立憑證,重複上述步驟並改選正式環境的 App ID 即可。
配置文件是一份集合,它列舉了與 App 相關的開發者、以及經註冊驗證過的測試裝置。內容包含憑證、裝置識別碼、App 的 Bundle ID 與各項權利。所有團隊成員都必須在測試裝置上安裝它。
~/Library/MobileDevice/Provisioning Profiles。aps-environment 鍵:Development profile 應為 development,Distribution profile 應為 production。你必須把 SSL 憑證與對應的私鑰一起放到執行 Provider 程式的伺服器上。
openssl pkcs12 -in CertificateName.p12 -out CertificateName.pem -nodes
App 必須先註冊,才能接收遠程通知。流程是:呼叫 registerForRemoteNotificationTypes:;在委派方法 application:didRegisterForRemoteNotificationsWithDeviceToken: 中取得 token;把 token 當作純二進位資料上傳給 Provider。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[ViewController alloc] init];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
// 註冊推送:同時訂閱提示、角標與聲音三種型別
[[UIApplication sharedApplication]
registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert
| UIRemoteNotificationTypeBadge
| UIRemoteNotificationTypeSound)];
// 判斷 App 是否由使用者點擊通知而啟動
if (launchOptions) {
NSDictionary *pushKey =
[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushKey) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"推送通知"
message:@"這是透過推送啟動的程序,可在這裡處理推送內容"
delegate:nil
cancelButtonTitle:@"知道了"
otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
#pragma mark - 註冊成功:取得並上傳 deviceToken
- (void)application:(UIApplication *)app
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
NSLog(@"apns -> 生成的 devToken: %@", token);
DeviceSender *sender = [[DeviceSender alloc] initWithDelegate:self];
[sender sendDeviceToPushServer:token];
}
#pragma mark - 註冊失敗
- (void)application:(UIApplication *)app
didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSLog(@"apns -> 註冊推送時發生錯誤: %@", err);
}
#pragma mark - 收到遠程通知
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
NSLog(@"apns -> 收到資料: %@", userInfo);
// 清除圖示角標
application.applicationIconBadgeNumber = 0;
NSDictionary *aps = [userInfo objectForKey:@"aps"];
if ([aps objectForKey:@"alert"] != NULL) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"推送訊息"
message:[aps objectForKey:@"alert"]
delegate:self
cancelButtonTitle:@"關閉"
otherButtonTitles:@"處理推送內容", nil];
[alert show];
}
}
deviceToken 會變動:使用者重裝 App、還原備份或系統更新後,token 都可能改變,因此每次啟動註冊後都應把最新 token 同步給伺服器,並在回饋服務回報失效時主動清理。
角標數字由伺服器決定:通知 payload 中的 badge 是絕對值而非增量,多個來源同時推送時容易互相覆蓋,需要伺服器端統一計算。
iOS 10 之後 API 已全面改版:本文的 UILocalNotification/registerForRemoteNotificationTypes: 這套寫法在 iOS 10 起被 UserNotifications 框架取代,改為 UNUserNotificationCenter 搭配 UNNotificationRequest,並統一了本地與遠程通知的處理方式。新專案請直接採用新 API,本文的機制與配置流程說明仍然適用。