iOS10 已經 “deprected” 我們的UILocalNotification 采用了全新的UNUserNotificationCenter;
1 首先,你需要引進<UserNotifications/UserNotifications.h>
#import <UserNotifications/UserNotifications.h>
2 然后,在AppDelegate.m中,完成推送通知的注冊和請求授權;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 獲取通知中心--單例 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; //設置代理 center.delegate = self; //獲取用戶的推送授權 iOS 10新方法 [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; //獲取當前的通知設置,UNNotificationSettings 是只讀對象,readOnly,只能通過以下方法獲取 [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { }]; return YES; }
3 完成注冊,之后是通過使用UNUserNotificationCenter 來實現推送通知;
在要使用本地通知時,通過單例(UNUserNotificationCenter)來實現,通過一個button的點擊來啟動通知為例:
#pramark mark - 點擊按鈕發送本地通知事件 - (void) buttonClickAction{ // > 使用 UNUserNotificationCenter 來管理通知-- 單例 UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; // > 需創建一個包含待通知內容的 UNMutableNotificationContent 對象,可變 UNNotificationContent 對象,不可變 // > 通知內容 UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init]; // > 通知的title content.title = [NSString localizedUserNotificationStringForKey:@"推送的標題" arguments:nil]; // > 通知的要通知內容 content.body = [NSString localizedUserNotificationStringForKey:@"======推送的消息體======" arguments:nil]; // > 通知的提示聲音 content.sound = [UNNotificationSound defaultSound]; // > 通知的延時執行 UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:content trigger:trigger]; //添加推送通知,等待通知即可! [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { // > 可在此設置添加后的一些設置 // > 例如alertVC。。 }]; }
iOS 10 遠程推送詳見 “ios10 UNNtificationRequest UNUserNotificationCenter的應用 推送之遠程推送”!
