在行動裝置上,任何時刻通常只有一個 App 處於前景並與使用者互動。當其他應用有值得關注的事情發生時,該如何即時告知使用者?答案就是通知機制。在 iOS 中,通知又常被稱為消息機制,主要分為兩大類:一類是由裝置本機觸發的本地通知(Local Notification),另一類是由伺服器下發的遠程推送(Remote / Push Notification)。
從使用者角度看,這兩種通知的呈現方式幾乎一致,都可以透過橫幅、警示框或標記數字等形式提醒使用者,點擊通知也能開啟對應的 App。但它們背後的實現原理卻截然不同。本文將帶你動手實作這兩種機制,並在後段補充說明「通知中心」的概念,避免初學者把兩者混淆。
本地通知由 App 本身觸發,是一種基於時間行為的提醒形式,例如鬧鐘定時、待辦事項提醒,或偵測到使用者長時間未使用而給出的喚回提示。建立一個本地通知大致可分為以下幾個步驟:
UILocalNotification 物件。fireDate。userInfo 綁定自訂參數。scheduleLocalNotification: 排程觸發,或用 presentLocalNotificationNow: 立即觸發。下面以「App 更新後、使用者長期未開啟」的喚回提醒為例。這個範例幾乎不涉及介面操作,所有邏輯都集中在 AppDelegate 中:App 啟動時若尚未取得通知授權,先請求使用者允許;無論使用者是否同意,都會觸發 didRegisterUserNotificationSettings: 代理方法,再依授權結果決定是否建立並排程通知。
#import "AppDelegate.h"
#import "KCMainViewController.h"
@implementation AppDelegate
#pragma mark - 應用代理方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
// 設定全域導覽列風格與顏色
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController = [[KCMainViewController alloc] init];
_window.rootViewController = mainController;
[_window makeKeyAndVisible];
// 若已取得通知授權則直接建立本地通知,否則先請求授權
// 注意:若從未請求過授權,設定中不會出現對應的通知項目
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
[self addLocalNotification];
} else {
[[UIApplication sharedApplication] registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound)
categories:nil]];
}
return YES;
}
#pragma mark 呼叫 registerUserNotificationSettings: 之後執行
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
if (notificationSettings.types != UIUserNotificationTypeNone) {
[self addLocalNotification];
}
}
#pragma mark 進入前台後清除圖標數字
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
#pragma mark - 私有方法
- (void)addLocalNotification {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0]; // 10 秒後觸發
notification.repeatInterval = 2; // 重複間隔
notification.alertBody = @"最近新增了許多有趣的功能,是否立即體驗?";
notification.applicationIconBadgeNumber = 1;
notification.alertAction = @"打開應用";
notification.alertLaunchImage = @"Default";
notification.soundName = @"msg.caf"; // 自訂提示音(需真機才能聽到)
notification.userInfo = @{@"id": @1, @"user": @"Kenshin Cui"};
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
// 不再需要時記得移除
- (void)removeNotification {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
@end
透過上述流程,我們可以在不依賴伺服器的情況下,讓 App 於指定時間精準地向使用者發出提醒,這正是本地通知最典型的應用場景。