您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 本地通知實作:排程、內容設定與接收處理

編輯:iOS 相關資訊

本地通知(Local Notification)適合用在「提醒由 App 自己產生」的情境:計時結束、待辦到期、每日簽到提醒。它不需要伺服器,也不消耗網路,但相對地,App 被終止後就無法再排新的通知,且所有排程都由使用者可控。

前提:要看到通知橫幅,請按 Home 鍵讓 App 進入背景;App 在前前景時通知不會以橫幅形式出現,而是走 didReceiveLocalNotification: 這條路徑。

完整實作

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 建立本地通知
    UILocalNotification *localnotifit = [[UILocalNotification alloc] init];

    if (localnotifit) {
        NSDate *now = [NSDate date];
        localnotifit.timeZone = [NSTimeZone defaultTimeZone];

        // 10 秒後觸發
        localnotifit.fireDate = [now dateByAddingTimeInterval:10.0];

        // 重複間隔(下限為每分鐘一次)
        localnotifit.repeatInterval = kCFCalendarUnitMinute;

        // 提醒內容
        localnotifit.alertBody = @"十秒後手機將會爆炸,趕快扔掉";

        // 鎖屏時「滑動來...」後面接的文字
        localnotifit.alertAction = @"解鎖(進入 App)";

        // 通知中心的標題
        localnotifit.alertTitle = @"提示";

        // 預設通知音效(只有真機能聽到)
        localnotifit.soundName = UILocalNotificationDefaultSoundName;

        // App 圖示上的紅色數字
        localnotifit.applicationIconBadgeNumber = 1;

        // 通知識別資訊,可在回呼中取用
        NSMutableDictionary *dic =
            [NSMutableDictionary dictionaryWithObject:@"LocalNotificationID" forKey:@"key"];
        localnotifit.userInfo = dic;

        // 排入系統
        [[UIApplication sharedApplication] scheduleLocalNotification:localnotifit];
    }

    // 註冊通知權限(iOS 8 之後的寫法)
    UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:
            UIUserNotificationTypeAlert |
            UIUserNotificationTypeBadge |
            UIUserNotificationTypeSound
            categories:nil];

    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

    return YES;
}

App 位於前景時收到通知

// 只有 App 在前景時才會走這裡
-(void)application:(UIApplication *)application
        didReceiveLocalNotification:(UILocalNotification *)notification {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
        message:@"恭喜你上當了" delegate:nil
        cancelButtonTitle:nil otherButtonTitles:@"我很開心", nil];
    [alert show];

    // 收到後清掉圖示上的數字
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    // 若要取消所有已排程的通知:
    // [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

各欄位的意義與眉角

  • fireDate + timeZone。兩者要一起看。fireDate 是一個絕對時刻,timeZone 決定它以哪個時區解讀;若使用者跨時區飛行,設定不當會讓通知在錯誤的時間跳出。
  • repeatInterval。它與 fireDate 搭配形成週期性排程,最小粒度為分鐘(kCFCalendarUnitMinute)。若需要「每個上班日下午三點」這種規則,用 NSCalendarUnitDay 加上特定 fireDate 會比逐筆排程乾淨。
  • alertTitle 是 iOS 8.2 才加入的屬性。在更早的系統上只有 alertBody 會顯示。
  • applicationIconBadgeNumber 是「設定值」而非「累加值」。它直接決定紅色圓圈顯示的數字,不會自動遞增。若有多筆通知,記得自行管理計數。
  • userInfo 是你自己的口袋。使用者點通知進入 App 時,可以從 didFinishLaunchingWithOptions: 的 launchOptions 或 didReceiveLocalNotification: 中取出,用來判斷該跳到哪個頁面。

從這段程式碼到現代寫法

上面這套 UILocalNotification 與 UIUserNotificationSettings 在 iOS 10 之後已被 UserNotifications.framework 取代,舊 API 雖仍可運作但不再建議用於新專案。新寫法的差異值得記住:

// 請求權限
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:
    (UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                      completionHandler:^(BOOL granted, NSError *error) { }];

// 建立通知內容
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"提示";
content.body  = @"十秒後手機將會爆炸,趕快扔掉";
content.sound = [UNNotificationSound defaultSound];
content.userInfo = @{@"key": @"LocalNotificationID"};

// 包裝成請求並加入排程
UNTimeIntervalNotificationTrigger *trigger =
    [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

NSString *identifier = [[NSUUID UUID] UUIDString];
UNNotificationRequest *request =
    [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];

[center addNotificationRequest:request withCompletionHandler:nil];

新架構有三個明顯好處:每筆通知都有 identifier,可以精準更新或取消單一通知(舊 API 只能全砍或全清);回呼統一走 UNUserNotificationCenterDelegate,前景顯示與使用者互動的處理集中在一處;而且與遠端推送共用同一套 content/request 模型,本地與遠端的程式碼可以大量重用。

最後提醒一個常被忽略的細節:使用者拒絕通知權限時,排程不會報錯,只是永遠不會顯示。所以別把「通知有沒有跳」當成功能正確與否的唯一驗證方式,記得在設定中把權限打開再測。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved