iOS 的推送通知分成兩類。遠程推送就像我們用微信時的體驗:手機鎖屏也照樣收到訊息,還會在螢幕上彈出提示。它需要 APNs 與自家伺服器配合,涉及憑證、裝置 token 註冊與重試機制,架構相對複雜。
本地推送則完全在裝置端排程,不需要伺服器參與,適合提醒事項、每日通知這類由時間觸發的固定排程。
本地通知由 UILocalNotification 實作,需要設定的屬性包括觸發時間、時區、顯示內容、聲音、圖示數字與 userInfo。
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
// 設定 10 秒後觸發
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
if (notification != nil) {
notification.fireDate = pushDate;
// timeZone 決定這則通知是否隨時區變動而改變。
// 設為 nil 時,通知會在「一段時間之後」觸發,而不是某個確切時刻。
notification.timeZone = [NSTimeZone defaultTimeZone];
// 不重複設定的話只會推送一次
notification.repeatInterval = kCFCalendarUnitDay;
// 不設定的話靜音
notification.soundName = UILocalNotificationDefaultSoundName;
// 不設定的話通知中心不顯示文字
notification.alertBody = @"推送內容";
notification.alertLaunchImage = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"jpg"];
notification.applicationIconBadgeNumber = 1;
// userInfo 方便之後比對與取消
NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
notification.userInfo = info;
// 加入排程前先檢查是否已存在相同 key 的通知,避免重複
UIApplication *app = [UIApplication sharedApplication];
BOOL status = YES;
for (UILocalNotification *item in app.scheduledLocalNotifications) {
if ([item.userInfo objectForKey:@"key"]) {
status = NO;
break;
}
}
if (status) {
[app scheduleLocalNotification:notification];
}
}
userInfo 是整個流程的關鍵。系統不提供「依識別碼查詢通知」的 API,實務上都是自訂一個 key 放進 userInfo,取消時再反查。
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iWeibo"
message:notification.alertBody
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
application.applicationIconBadgeNumber -= 1;
}
要注意的是,如果 App 當時正在前台執行,系統預設不會幫你顯示任何東西,必須自己在這個方法裡處理呈現。另外 UIAlertView 在 iOS 8 之後已被標記為廢棄,新專案請改用 UIAlertController。
UIApplication *app = [UIApplication sharedApplication];
NSArray *localArray = [app scheduledLocalNotifications];
if (localArray) {
for (UILocalNotification *noti in localArray) {
NSDictionary *dict = noti.userInfo;
NSString *inKey = [dict objectForKey:@"key"];
if ([inKey isEqualToString:@"對應的key值"]) {
[app cancelLocalNotification:noti];
break;
}
}
}
如果key 對應的通知不存在,就什麼也不做即可,不需要先建立一個空的 notification 再取消,那是多餘的。
從 iOS 10 開始,UILocalNotification 已被 UNUserNotificationCenter 取代。新架構把「要求授權」與「建立通知內容」拆成兩件事:先呼叫 requestAuthorizationWithOptions 取得使用者同意,再用 UNMutableNotificationContent 描述內容、UNNotificationRequest 綁定 trigger,最後 addRequest: 加入排程。舊 API 在 iOS 10 上仍可運作,但新專案沒有理由再用它。
本地推送與遠程推送的深入探討,可參考 Apple 官方 Local and Remote Notification Programming Guide,以及 Ray Wenderlich 的 Apple Push Notification Services 系列教學。若要串接第三方服務,極光推送與 Firebase Cloud Messaging 都有完整的 iOS 文件。