iOS 有兩種通知機制:本地推送(Local Notification)與遠端推送(Remote / Push Notification)。兩者的目的相同——提醒使用者有新鮮事發生,吸引他回來打開 App。
差異在來源:本地通知由 App 自己在系統上排程,即使 App 在背景甚至已關閉,約定時間一到仍會發出;遠端通知則由你的伺服器經由 Apple 的 APNS 轉發到手機。此外,本地通知也能由伺服器間接控制(例如收到新訊息時排入一則提醒),但前提是 App 必須先被啟動過。遠端推播在業界使用得較多,本文先談本地推送。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[application registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
UIUserNotificationTypeAlert |
UIUserNotificationTypeBadge |
UIUserNotificationTypeSound
categories:nil]];
return YES;
}
這一步會讓系統跳出權限詢問視窗,使用者可以選擇允許「提示、角標、聲音」中的哪些項目。
- (IBAction)localPushNow:(id)sender {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UILocalNotification *notification = [[UILocalNotification alloc] init];
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
if (notification != nil) {
notification.fireDate = pushDate; // 10 秒後觸發
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.repeatInterval = kCFCalendarUnitDay; // 每日重複
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertBody = @"hello,world";
notification.applicationIconBadgeNumber = 0;
notification.userInfo = @{@"name": @"test"}; // 攜帶自訂資料
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
});
}
幾個屬性的意義:fireDate 決定觸發時刻;repeatInterval 設定重複週期;userInfo 可攜帶任意 plist 可序列化的資料,讓 App 收到通知時知道該做什麼;applicationIconBadgeNumber 控制 App 圖示上的紅色數字。
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(@"%@", notification.alertBody);
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(0, 0, 160, 20);
label.layer.cornerRadius = 10;
label.backgroundColor = [UIColor blackColor];
label.text = notification.alertBody;
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:12];
label.textAlignment = NSTextAlignmentCenter;
[self.window addSubview:label];
}
排程時若看到:
Attempting to schedule a local notification with a sound but haven't received permission from the user to play sounds
或:
Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts
代表使用者在系統設定中關閉了對應的通知權限。請先確認是否已完成註冊,並引導使用者到「設定 → 通知」中重新開啟。
1. 別忘了取消。若通知已無意義(例如使用者已讀取訊息),請主動呼叫 cancelLocalNotification: 或 cancelAllLocalNotifications,否則使用者會收到過期的提醒。
2. 通知數量有上限。系統同時排程的本地通知上限為 64 則,超出會被丟棄,長週期的重複通知請謹慎使用。
3. 主執行緒更新 UI。上面的範例把排程丟到背景佇列,但 didReceiveLocalNotification: 中的 UI 操作必須在主執行緒執行。
4. UILocalNotification 已被取代。自 iOS 10 起,本地與遠端通知統一由 UserNotifications 框架處理,UILocalNotification 與 UIApplication 上的相關 API 皆已標記為 deprecated。新專案請改用:
#import <UserNotifications/UserNotifications.h>
// 請求授權
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:UNAuthorizationOptionAlert |
UNAuthorizationOptionSound |
UNAuthorizationOptionBadge
completionHandler:^(BOOL granted, NSError *error) { }];
// 排程本地通知
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"提醒";
content.body = @"hello,world";
content.sound = [UNNotificationSound defaultSound];
content.userInfo = @{@"name": @"test"};
UNTimeIntervalNotificationTrigger *trigger =
[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
UNNotificationRequest *request =
[UNNotificationRequest requestWithIdentifier:@"local-1" content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter]
addNotificationRequest:request withCompletionHandler:nil];
新框架的好處是:本地與遠端通知的程式碼完全一致、每則通知都有唯一 identifier 便於更新與取消、並支援通知擴充與自訂 UI,是遷移時值得優先投入的方向。