不需要連網,由 App 透過系統發出的通知。與遠端推送的差別在於內容完全產生在本機。
定時提醒類的功能,例如遊戲的體力回滿、記帳 App 的每日提醒、鬧鐘與備忘錄等。
1. 建立 UILocalNotification 物件
2. 設定各項屬性
fireDate:觸發時間alertBody:通知內容文字alertTitle:鎖屏時顯示的標題soundName:提示音名稱applicationIconBadgeNumber:圖示上的數字徽章timeZone:時區userInfo:自訂的附帶資料3. 把通知排入程式的排程中
4. 處理使用者點擊通知後的行為
這部分要分兩種狀態討論:
didReceiveLocalNotification:didFinishLaunchingWithOptions: 處理,通知內容會放在 launchOptions 參數中(1)AppDelegate.m 中的權限申請與啟動處理
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
// iOS 8 之後需主動詢問使用者是否允許接收通知。
// 首次執行時系統會跳出提示框徵求同意。
UIUserNotificationType type = UIUserNotificationTypeAlert
| UIUserNotificationTypeSound
| UIUserNotificationTypeBadge;
UIUserNotificationSettings *setting =
[UIUserNotificationSettings settingsForTypes:type categories:nil];
[application registerUserNotificationSettings:setting];
}
// 若是因點擊通知而啟動,通知內容會存在 launchOptions 中
UILocalNotification *notification =
launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 300, 200)];
label.backgroundColor = [UIColor blueColor];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:30];
label.textColor = [UIColor whiteColor];
label.text = [NSString stringWithFormat:@"%@", notification.userInfo];
[self.window.rootViewController.view addSubview:label];
// 清掉圖示上的紅色數字
[application setApplicationIconBadgeNumber:0];
}
return YES;
}三種狀態的行為整理:
1. App 在前景,通知到時 → 直接執行 didReceiveLocalNotification: 2. App 在背景,通知到時 → 點擊查看後才執行該方法 3. App 已結束,通知到時 → 該方法不執行,但 didFinishLaunchingWithOptions: 一定會被執行,通知內容可從 launchOptions 取得
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 250, 300, 200)];
label.backgroundColor = [UIColor grayColor];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:30];
label.textColor = [UIColor whiteColor];
label.text = [NSString stringWithFormat:@"%@", notification.userInfo];
[self.window.rootViewController.view addSubview:label];
[application setApplicationIconBadgeNumber:0];
}(2)在需要排程的地方建立通知
// 1. 建立通知物件
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 2. 設定屬性
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10]; // 10 秒後發送
notification.alertBody = @"這是一則新通知";
notification.userInfo = @{@"name": @"張三", @"age": @20};
notification.applicationIconBadgeNumber = 2;
// 3. 加入程式的排程
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:notification];最後提醒:iOS 10 之後,本地與遠端通知已統一改用 UserNotifications 框架(UNUserNotificationCenter、UNNotificationRequest),上述 UILocalNotification 系列 API 已被標記為棄用。新專案請直接採用新框架,舊專案維護時則可參考以上邏輯。
Demo:https://github.com/TigerCui/LocalNotification.git