透過 UILocalNotification,你可以在 App 內部安排定時提醒,而且即使 App 被切到背景甚至關閉也照樣會發作。要改角標數字、彈一個提示框、播放聲音,都在同一個類別裡設定,寫起來相當省事。
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification != nil) {
NSDate *now = [NSDate new];
notification.fireDate = [now dateByAddingTimeInterval:15]; // 15 秒後觸發
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = @"定時推送通知!";
notification.soundName = @"default";
[notification setApplicationIconBadgeNumber:22];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
我另外寫了一個小 Demo,看過一次就知道怎麼用,某些場合還蠻實用的。
原始碼:https://github.com/andypan1314/LocalNotificationTest
例如每天下午四點提醒一次,只要改用 repeatInterval 讓系統幫你重複即可:
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification != nil) { // 先確認系統支援本地通知
notification.fireDate = [NSDate dateWithTimeIntervalSince1970:16 * 60 * 60 * 24];
notification.repeatInterval = kCFCalendarUnitWeekday; // 重複單位:週
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = @"哇哇哇";
notification.applicationIconBadgeNumber = 0; // App 右上角數字
notification.soundName = UILocalNotificationDefaultSoundName;
// notification.alertAction = NSLocalizedString(@"美女呀", nil); // 提示框按鈕文字
notification.hasAction = NO;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
repeatInterval 是「間隔單位」而不是「間隔數量」,也就是說它決定重複的粒度是天、週還是月,不會讓你設定「每 3 天」。另外 App 一共只能排入有限數量的待發通知(iOS 8 之後上限為 64 條),太多會被系統丟掉最舊的,記得在送出前自行清理。
以上就是本地定時通知的基本用法,簡單卻很實在。