iOS 的訊息提示有兩條路:一條是走伺服器的遠程推送 APNS,另一條是完全在本機排程的 UILocalNotification。後者不需要網路、不需要後端,非常適合做「每天八點提醒喝水」這類規則固定的提示。
UILocalNotification *notifity = [[UILocalNotification alloc] init]; NSDateFormatter *formattr = [[NSDateFormatter alloc] init]; [formattr setDateFormat:@"HH:mm"]; NSDate *now = [formattr dateFromString:strTimer]; notifity.fireDate = now; // 觸發時間 notifity.timeZone = [NSTimeZone defaultTimeZone]; // 時區 notifity.repeatInterval = NSDayCalendarUnit; // 重複單位:日 notifity.alertBody = @"這是一個通知"; // 通知內容 notifity.soundName = UILocalNotificationDefaultSoundName; // 提示音 // 通知的提示方式還可搭配 alertAction 與 applicationIconBadgeNumber [[UIApplication sharedApplication] scheduleLocalNotification:notifity];
repeatInterval 支援的單位相當多,除了本例的 NSDayCalendarUnit,還有 NSWeekdayCalendarUnit(週)、NSMinuteCalendarUnit(分)、NSSecondCalendarUnit(秒)、NSMonthCalendarUnit(月)與 NSYearCalendarUnit(年)。搭配 fireDate 就能組出各種排程規則。
如果希望使用者點擊通知後,App 能知道「要跳到哪個頁面」,可以用 userInfo 攜帶資料。
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"]; notification.userInfo = dic;
App 正在執行時收到通知,會走 AppDelegate 的這個回调:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
if (notification) {
NSDictionary *userInfo = notification.userInfo;
NSString *obj = [userInfo objectForKey:@"key"];
NSLog(@"%@", obj);
}
}
要注意的是,若 App 當時在背景,這個方法不會立刻被執行,而是等使用者實際點擊通知、App 回到前景時才觸發。因此有兩種狀態需要分別處理:冷啟動時可從 didFinishLaunchingWithOptions 的 launchOptions 參數中取出通知,熱啟動則走上述回调。
取消的方式有兩種,分別對應「取消一筆」與「全部清空」:
[[UIApplication sharedApplication] cancelLocalNotification:localNotification]; [[UIApplication sharedApplication] cancelAllLocalNotification];
實務上建議在登出、或使用者於設定中關閉提醒時,明確取消對應的通知,否則使用者已經關掉功能卻仍收到提示,體驗會很差。另外提醒一下,UILocalNotification 這套 API 在 iOS 10 之後已被 UserNotifications 框架取代,新專案請直接使用 UNUserNotificationCenter。