iOS 推播可分為本地通知與遠程推送。本地通知由 App 排程,適合提醒、計時或離線提示;遠程推送則由伺服器透過 APNS 發送。
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertBody = @"Helloworld";
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
可透過 userInfo 標記通知,方便後續取消特定通知。新專案也可改用 UserNotifications framework。
伺服器將訊息提交到 APNS,APNS 再依 device token 將通知送達裝置。若裝置離線,APNS 會保留最新通知,待裝置上線後再派送。
需要建立 CSR、在 Developer 後台產生推送證書、下載並匯入鑰匙串,再透過 OpenSSL 合併成伺服器可用的 PEM 或 P12 檔案。
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
AppDelegate 可實作 didRegisterForRemoteNotificationsWithDeviceToken 取得 token,並於 didReceiveRemoteNotification 處理推播內容。