本地通知適合那些不需要伺服器的提醒場景:待辦事項到期、離開某個區域、每日簽到提醒等。以下把建立、接收、取消三個環節整理清楚。
UILocalNotification *notification = [[UILocalNotification alloc] init];
if (notification) {
NSDate *now = [NSDate new];
notification.fireDate = [now dateByAddingTimeInterval:10]; // 10 秒後觸發
notification.repeatInterval = 0; // 不重複
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.applicationIconBadgeNumber = 1; // App 角標數字
notification.soundName = UILocalNotificationDefaultSoundName;
// 也可指定自訂音效:notification.soundName = @"sound.wav";
// 去掉下面兩行,就不會彈出提示框,只更新角標
notification.alertBody = @"通知內容";
notification.alertAction = @"打開"; // 提示框上的按鈕標題
// notification.hasAction = NO; // 設為 NO 時 alertAction 不顯示
// userInfo 用於後續辨識與撤銷這則通知,
// 觸發時也能從中取出自訂參數
NSDictionary *infoDict = @{ @"key": @"value" };
notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
// 透過 userInfo 判斷是哪一則通知,決定後續動作
if ([[notification.userInfo objectForKey:@"key"] isEqualToString:@"value"]) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"系統提示"
message:@"你的系統存在嚴重威脅"
delegate:nil
cancelButtonTitle:@"關閉"
otherButtonTitles:nil];
[alert show];
}
// 收到後清掉角標
application.applicationIconBadgeNumber = 0;
}
如果使用者是從 App 圖示進入(而非點擊通知),也可以在此清除角標:
- (void)applicationDidBecomeActive:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}
// 取得目前所有已排程的本地通知
NSArray *notificaitons = [[UIApplication sharedApplication] scheduledLocalNotifications];
if (!notificaitons || notificaitons.count <= 0) {
return;
}
// 取消某一則特定的通知
for (UILocalNotification *notify in notificaitons) {
if ([[notify.userInfo objectForKey:@"key"] isEqualToString:@"value"]) {
[[UIApplication sharedApplication] cancelLocalNotification:notify];
break;
}
}
// 取消全部
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
registerUserNotificationSettings:)才能排程,否則通知不會觸發,只會在控制台留下警告。fireDate 是「系統時間」,使用者改了時區或手動調時間都可能影響觸發。若要求嚴格準時,建議改用 repeatCalendar 搭配 timeZone 明確指定。UILocalNotification 已被 UserNotifications 框架取代,新專案請改用 UNNotificationRequest,它能更精細地管理與查詢通知佇列。