您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 本地推送 UILocalNotification 完整流程

編輯:iOS 開發綜合

本地通知適合那些不需要伺服器的提醒場景:待辦事項到期、離開某個區域、每日簽到提醒等。以下把建立、接收、取消三個環節整理清楚。

一、建立通知

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];

實務提醒

  • iOS 8 之後必須先取得使用者授權(registerUserNotificationSettings:)才能排程,否則通知不會觸發,只會在控制台留下警告。
  • fireDate 是「系統時間」,使用者改了時區或手動調時間都可能影響觸發。若要求嚴格準時,建議改用 repeatCalendar 搭配 timeZone 明確指定。
  • App 被終止後,已排程的本地通知仍然有效,這是它與背景任務最大的差別,也是它最實用的地方。
  • iOS 10 起 UILocalNotification 已被 UserNotifications 框架取代,新專案請改用 UNNotificationRequest,它能更精細地管理與查詢通知佇列。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved