前言
iOS 10 把 UIKit 裡的 UILocalNotification 標記為廢棄,改由全新的 UserNotifications Framework 接手。從此通知有了自己的命名空間 UN(這待遇確實沒別人),還附帶兩個 extension 與介面體驗優化,可說是蘋果的看板功能之一,自然也成了開發時的重點項目。
本文把 iOS 10 底下的本地通知整理出來,都是程式碼,就不多囉嗦,直接看範例與註解。
#import <UserNotifications/UserNotifications.h>
#import "AppDelegate.h"
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 用 UNUserNotificationCenter 管理所有通知
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// 監聽回呼
center.delegate = self;
// iOS 10 必須用這個方法才能拿到授權
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// 依授權結果啟用或停用功能
}];
// UNNotificationSettings 是唯讀物件,不能改,只能透過這個方法讀
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
}];
return YES;
}
#pragma mark - UNUserNotificationCenterDelegate
// 通知即將呈現前的處理,等於多了一次修改內容的機會
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
// 1. 處理通知
// 2. 完成後呼叫 completionHandler,決定前台顯示形式
completionHandler(UNNotificationPresentationOptionAlert);
}
@end
// 用 UNNotification 送本地通知
+ (void)registerNotification:(NSInteger)alerTime {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
// 內容要用 UNMutableNotificationContent,UNNotificationContent 是不可變的
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body" arguments:nil];
content.sound = [UNNotificationSound defaultSound];
// alerTime 秒後觸發
UNTimeIntervalNotificationTrigger *trigger =
[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:alerTime repeats:NO];
UNNotificationRequest *request =
[UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知"
message:@"成功添加推送"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:nil];
[alert addAction:cancelAction];
[[UIApplication sharedApplication].keyWindow.rootViewController
presentViewController:alert animated:YES completion:nil];
}];
}
+ (void)registerLocalNotificationInOldWay:(NSInteger)alertTime {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime]; // 觸發時間
NSLog(@"fireDate=%@", notification.fireDate);
notification.timeZone = [NSTimeZone defaultTimeZone]; // 時區
notification.repeatInterval = kCFCalendarUnitSecond; // 重複間隔
notification.alertBody = @"該起床了...";
notification.applicationIconBadgeNumber = 1;
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知參數
NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"開始學習 iOS 開發了" forKey:@"key"];
notification.userInfo = userDict;
// iOS 8 之後需要這個註冊才能拿到授權
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert
| UIUserNotificationTypeBadge
| UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
notification.repeatInterval = NSCalendarUnitDay;
} else {
notification.repeatInterval = NSDayCalendarUnit;
}
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
新舊最大的差別在於:舊寫法把「內容」與「觸發條件」攤在一個物件上,新寫法拆成 content 與 trigger 兩塊,再用 request 組起來,最後交給 center。好处是通知變成可以被識別、被查詢、被更新的實體——只要 identifier 相同,後送的通知就會覆蓋前一則。這也是為什麼 request 一定要給 identifier,隨便重複的命名會互相打架。
本文整理自 iOS 10 相關文件,以上就是本地通知的遷移重點。