本地通知能在不依賴伺服器的情況下,於指定時間觸發提醒。以下示範如何在 App 中註冊並處理本地通知。
註:按 Home 鍵讓 App 進入後台運行時,方可看到通知效果。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 註冊本地通知
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif) {
// 獲取當前時間
NSDate *now = [NSDate date];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// 10 秒後開始通知
localNotif.fireDate = [now dateByAddingTimeInterval:10.0];
// 重複間隔(下限為每分鐘通知一次)
localNotif.repeatInterval = kCFCalendarUnitMinute;
// 提醒內容
localNotif.alertBody = @"十秒後手機將會爆炸,趕快扔掉";
// 鎖屏狀態下,「滑動來」後面緊接的文字
localNotif.alertAction = @"解鎖(進入App)";
// 通知欄裡的通知標題
localNotif.alertTitle = @"提示";
// 默認的通知聲音(只有在真機上才會聽到)
localNotif.soundName = UILocalNotificationDefaultSoundName;
// 圖標右上角的紅色數字
localNotif.applicationIconBadgeNumber = 1;
// 通知標識(用於後續取消或識別)
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:@"LocalNotificationID" forKey:@"key"];
localNotif.userInfo = dic;
// 將通知添加到系統中
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
// 註冊通知(iOS 8 之後的方法)
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
return YES;
}
// 接收到通知後觸發的方法,只有在 App 進入前台時才會執行
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜你上當了" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"我很開心", nil];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[alert show];
// 取消通知
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
}
關鍵在於透過 fireDate 設定觸發時間、repeatInterval 設定重複間隔、alertBody 與 alertTitle 設定提醒內容,最後呼叫 scheduleLocalNotification: 將通知排入系統。而 didReceiveLocalNotification: 則是 App 在前台時收到通知的回調,可在此處理自訂邏輯或清除角標數字。