一、介紹
通知和推送是應用程序中很重要的組成部分。本地通知可以為應用程序注冊一些定時任務,例如鬧鍾、定時提醒等。遠程推送則更強大,提供了一種通過服務端主動推送消息到客戶端的方式,服務端可以更加靈活地控制通知邏輯,例如廣告的推送、定時任務的提醒、即時通信類應用離線消息的提醒等。本文先着重着介紹本地通知,由於iOS系統的不斷更新,本地通知的API也需要根據設備的系統來進行選擇和兼容。
- 在iOS10之前,開發者需要使用UILocalNotification類來實現本地通知;
- 在iOS10之后,蘋果為了加強對通知和推送的統一管理,提高通知界面的高可定制性,引入了UserNotification框架。
二、UILocalNotification
1、簡介
ULLocalNotification是iOS8中的一個類(In iOS 8.0 and later),用來實現本地通知功能。通知,實際上是由iOS系統管理的一個功能,比如注冊了通知,則系統會在通知被觸發時給應用程序發送消息。但是,ULLocalNotification僅能提供開發者去編輯消息,消息推送到app上展示的樣式和交互則是固定的,開發者自定制的難度相當大。
2、添加步驟
- 創建通知對象
- 設置觸發時間
- 設置通知屬性
- 執行本地通知
/// 添加本地推送 -(void)addLocalNotification { //1、創建通知對象 UILocalNotification *notification = [[UILocalNotification alloc] init]; //2、設置觸發時間 notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];//5秒后 //3、設置通知屬性 notification.alertTitle = @"本地推送"; /// 通知標題 notification.alertBody = @"HELLO,歡迎哥的到來"; /// 通知主體 notification.applicationIconBadgeNumber = 1; /// 應用程序圖標的消息數 notification.hasAction = YES; /// 待機界面開啟左滑按鈕 notification.alertAction = @"打開應用"; /// 待機界面的滑動按鈕提示 notification.userInfo = @{@"name":@"xyq"}; /// 傳遞的用戶數據 notification.soundName = UILocalNotificationDefaultSoundName; /// 在收到通知時播放的聲音,默認消息聲音 //4、執行本地通知 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; }
3、處理邏輯
- 申請通知授權
- 添加本地通知
- 收到通知處理
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. //如果已經得到授權,就直接添加本地通知,否則申請詢問授權 if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) { //開始授權 [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil]]; } //如果我們的應用程序處於關閉狀態時,然后被通知喚醒后,直接在完成正常啟動流程的代理函數中獲取通知對象 UILocalNotification *notification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocationKey]; if (notification) { NSDictionary *userInfo = notification.userInfo; NSLog(@"1----notification------- %@",notification); NSLog(@"1----userInfo------- %@",notification.userInfo); } return YES; }
/// 當用戶點擊允許或者不允許時,會執行如下代理方法,我們在其中實現處理邏輯 -(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { if (notificationSettings.types != UIUserNotificationTypeNone) { [self addLocalNotification]; } } /// 當我們的應用進入前台時,需要清除應用圖標的數字 -(void)applicationWillEnterForeground:(UIApplication *)application { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; } /// 當我們的應用程序在前台或者從后台進入前台時,收到本地通知 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { if (notification) { NSDictionary *userInfo = notification.userInfo; NSLog(@"2----notification------- %@",notification); NSLog(@"2----userInfo------- %@",notification.userInfo); } }
4、演示示例
2019-11-01 15:01:33.991404+0800 本地推送[95797:2946024] 2----notification------- <UIConcreteLocalNotification: 0x600000932080>{fire date = Friday, November 1, 2019 at 3:01:33 PM China Standard Time, time zone = (null), repeat interval = 0, next fire date = (null), user info = { name = xyq; }} 2019-11-01 15:01:33.991612+0800 本地推送[95797:2946024] 2----userInfo------- { name = xyq; }

三、UserNotification
1、簡介
UserNotification是iOS10后蘋果提出的一個整合的通知和推送框架,對之前的通知和推送功能進行了全面的重構和優化,功能更強大,定制更靈活。表現如下:
- 通知處理代碼從AppDelegate中剝離
- 通知的注冊、設置、處理更加結構化,更易於進行模塊的開發
- 支持自定義通知音效和啟動圖
- 支持向通知內容中添加媒體附件,例如音效、視頻
- 支持開發者定義多套通知展示模塊
- 支持完全自定義的通知界面
- 支持自定義通知中的用戶交互按鈕
- 通知的觸發更加容易管理
2、核心類結構圖

- UNNotificationCenter:通知管理中心單例設計,負責通知的注冊、接收通知后的回調處理等,是UserNofitication框架的核心。
- UNNotification:通知對象,其中封裝了通知請求
- UNNoticationSettings:通知相關設置
- UNNotificationCategory:通知模板
- UNNotificationAction:用於定義通知模板中的用戶交互行為
- UNNotificationRequest:注冊通知請求,其中定義了通知的內容和觸發方式
- UNNotificationResponse:接收到通知后的回執
- UNNotificationContent:通知的具體內容
- UNNotificationAttachment:通知所攜帶的附件,為通知內容添加
- UNNotificationSound:定義通知音效, (音頻文件必須位於bundle或者Library/Sounds目錄下)
- UNNotificationTrigger:通知觸發器,由其子類具體定義
- UNPushNotificationTrigger:遠程推送觸發器,UNNotificationTrigger的子類
- UNTimerInrevalNotificationTrigger:計時器觸發器,UNNotificationTrigger的子類
- UNCalendarNotificationTrigger:周期日歷觸發器,UNNotificationTrigger的子類
- UNLocationNotificationTrigger:地域觸發器,UNNotificationTrigger的子類
- UNNotificationCenterDelegate:協議,其中方法用於監聽通知狀態
注意:
- 媒體附件大小

- 對於收到的附件通知,可以把消息下拉看到完整的附件內容(見下面的代碼示例圖所展示的樣子)
- 內容附件實例中options配置字典鍵/值作用,本示例代碼中options默認置為nil

- 附件資源放置位置Bundle目錄下

3、權限申請 和 附件資源包位置(Bundle目錄下)
//進行用戶權限申請 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert|UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) { //在block中會傳入布爾值granted,表示用戶是否同意 if (granted) { //如果用戶申請權限成功,則可以設置通知中心的代理 //[UNUserNotificationCenter currentNotificationCenter].delegate = self; //添加通知 [self addNormalLocationNotification]; } }];
4、創建通知
4-1:普通通知
/// 創建普通的通知 - (void)addNormalLocationNotification { //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @2; //設置通知的內容 content.body = @"iOS10新通知內容,普通通知,歡迎哥來了"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置觸發器 //1-計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //2-周期日歷觸發器 /* NSDateComponents *components = [[NSDateComponents alloc] init]; components.year = 2019; components.month = 11; components.day = 2; UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO]; //3-地域觸發器 CLRegion *region = [[CLCircularRegion alloc] initWithCenter:CLLocationCoordinate2DMake(33.0, 110.0) radius:100 identifier:@"region"]; UNLocationNotificationTrigger *locationTrigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:NO]; */ //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@"添加通知成功"); } }]; }
4-2:圖片通知
//創建圖片附件通知 -(void)addImageAttachLocationNotification { /* attachments:雖然這是一個數組,但是系統的通知模板只能展示其中的一個附件,設置多個附件也不會有額外的效果,但是如果開發者自定義通知模板UI, 次數組就派上用場了。 */ //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置圖片附件 UNNotificationAttachment *imageAttach = [UNNotificationAttachment attachmentWithIdentifier:@"imageAttach" URL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"]] options:nil error:nil]; content.attachments = @[imageAttach]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,圖片附件通知,歡迎哥來了"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }
4-3:音頻通知
//創建音頻附件通知 -(void)addAudioAttachLocationNotification { /* attachments:雖然這是一個數組,但是系統的通知模板只能展示其中的一個附件,設置多個附件也不會有額外的效果,但是如果開發者自定義通知模板UI, 次數組就派上用場了。 */ //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置圖片附件 UNNotificationAttachment *soundAttach = [UNNotificationAttachment attachmentWithIdentifier:@"soundAttach" URL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]] options:nil error:nil]; content.attachments = @[soundAttach]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,音頻附件通知,歡迎哥來了"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }
4-4:視頻通知
//創建視頻附件通知 -(void)addMoiveAttachLocationNotification { /* attachments:雖然這是一個數組,但是系統的通知模板只能展示其中的一個附件,設置多個附件也不會有額外的效果,但是如果開發者自定義通知模板UI, 次數組就派上用場了。 */ //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置圖片附件 UNNotificationAttachment *moiveAttach = [UNNotificationAttachment attachmentWithIdentifier:@"moiveAttach" URL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"moive" ofType:@"mov"]] options:nil error:nil]; content.attachments = @[moiveAttach]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,視頻附件通知,歡迎哥來了"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }

5、使用模板
除了上面介紹的強大的附件通知外,我們還可以把UserNotification提供的模板功能和用戶行為利用起來。在iOS系統中,聊天類軟件常常采用后台推送的方式推送消息,用戶可以在不進入應用程序的情況下,直接在桌面回復通過通知推送過來的消息,這種功能就是通過UNNotificationCategory和UNNotificationAction用戶行為來實現的。對於文本回復框,UserNotification框架提供了UNTextInputNotificationAction類,也即UNNotificationAction的子類。
5-1:UNTextInputNotificationAction創建文本回復框
//支持在桌面對本地通知消息進行回復 -(void)supportLocationNotificationReply { //創建回復框 //UNNotificationActionOptionAuthenticationRequired: 需要在解開鎖屏后使用 UNTextInputNotificationAction *inputAction = [UNTextInputNotificationAction actionWithIdentifier:@"action" title:@"回復" options:UNNotificationActionOptionAuthenticationRequired textInputButtonTitle:@"發送" textInputPlaceholder:@"請輸入回復內容"]; //創建通知模板 UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategoryText" actions:@[inputAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,普通通知,歡迎哥來了,期待你的回復!!!!"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置通知模板 //categoryIdentifier要與上面創建category的標識保持一致 content.categoryIdentifier = @"myNotificationCategoryText"; [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]]; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }

5-2:UNNotificationAction創建用戶交互按鈕
//支持在桌面對本地通知進行按鈕交互 -(void)supportLocationNotificationUserInterfaceButton { //創建交互按鈕(系統模板最多支持添加4個交互按鈕) //UNNotificationActionOptionNone: 無設置 UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action" title:@"用戶交互按鈕1" options:UNNotificationActionOptionNone]; UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action" title:@"用戶交互按鈕2" options:UNNotificationActionOptionNone]; UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action" title:@"用戶交互按鈕3" options:UNNotificationActionOptionNone]; UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action" title:@"用戶交互按鈕4" options:UNNotificationActionOptionNone]; //創建通知模板 UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategoryButton" actions:@[action1,action2,action3,action4] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,普通通知,歡迎哥來了!!!!"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置通知模板 //categoryIdentifier要與上面創建category的標識保持一致 content.categoryIdentifier = @"myNotificationCategoryButton"; [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]]; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationDefault" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }

6、通知擴展
通過UserNotification框架,開發者已經可以完成從前很難實現的效果。然后這都不是這個框架最強大的地方,它的最強大的功能是通過擴展實現完全自定義的通過UI界面。也即Notification Content Extension。在項目新建一個Target后,然后選擇Notification Content Extension擴展文件並創建,此時這個擴展文件自帶了一個故事板storyBoard和一個NotificationViewCenter類,開發者可以在storyBoard中或者NotificationViewCenter中直接定制需要的UI界面即可,具體方法可以去看API。需要注意的是,NotificationViewCenter類自動遵守了UNNotificationContentExtension協議,這個協議專門用來處理自定義的通知UI的內容展示。
注意:
在自定義的的通知界面上,雖然可以放置按鈕或者任何UI控件,但其不能進行用戶交互,唯一可以進行交互的方式是通過協議中的媒體按鈕及其回調方法。
//當用戶點擊通知中的用戶交互按鈕時會調用,開發者可以從notification對象中拿到附件等內容進行UI刷新 - (void)didReceiveNotification:(UNNotification *)notification; - (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion; //返回媒體按鈕位置 @property (nonatomic, readonly, assign) CGRect mediaPlayPauseButtonFrame; //返回媒體按鈕顏色 @property (nonatomic, readonly, copy) UIColor *mediaPlayPauseButtonTintColor; //點擊播放和暫停播放按鈕的回調 - (void)mediaPlay; - (void)mediaPause; //打開和關閉通知的回調 - (void)performNotificationDefaultAction; - (void)dismissNotificationContentExtension //媒體開始播放和暫停的回調 - (void)mediaPlayingStarted; - (void)mediaPlayingPaused .
當定義好通知的UI模板后,若要使用,還需要在Notification Content擴展中的info.plist文件的NSExtension的NSExtentionAttributes字典中進行一些配置。配置鍵如下:

6-1:創建擴展

6-2:配置plist

6-3:定制界面

// NotificationViewController.m // MyNotificationContentExtension #import "NotificationViewController.h" #import <UserNotifications/UserNotifications.h> #import <UserNotificationsUI/UserNotificationsUI.h> @interface NotificationViewController () <UNNotificationContentExtension> @property (nonatomic, strong) UILabel *customTitleLabel1; @property (nonatomic, strong) UILabel *customTitleLabel2; @property (nonatomic, strong) UIImageView *customImageView1; @property (nonatomic, strong) UIImageView *customImageView2; @end @implementation NotificationViewController - (void)viewDidLoad { [super viewDidLoad]; //屏幕寬 CGFloat screen_width = [UIScreen mainScreen].bounds.size.width; self.view.backgroundColor = [UIColor redColor]; //自定義Label self.customTitleLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, screen_width, 40)]; self.customTitleLabel1.textColor = [UIColor whiteColor]; self.customTitleLabel1.textAlignment = NSTextAlignmentCenter; self.customTitleLabel1.backgroundColor = [UIColor greenColor]; //自定義UIImageView self.customImageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, screen_width/2, 100)]; self.customImageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(screen_width/2, 40, screen_width/2, 100)]; self.customImageView1.backgroundColor = [UIColor purpleColor]; self.customImageView2.backgroundColor = [UIColor blueColor]; //自定義Label self.customTitleLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.customImageView1.frame)+20, screen_width, 40)]; self.customTitleLabel2.textColor = [UIColor whiteColor]; self.customTitleLabel2.textAlignment = NSTextAlignmentCenter; self.customTitleLabel2.backgroundColor = [UIColor orangeColor]; //添加控件 [self.view addSubview:self.customTitleLabel1]; [self.view addSubview:self.customTitleLabel2]; [self.view addSubview:self.customImageView1]; [self.view addSubview:self.customImageView2]; } /** 收到通知時觸發,但是這個是退出進程之后才使用,只適用於遠程推送(所以本地推送,這兩個方法是不會執行的) 拿到推送通知內容,刷新自定義的UI */ - (void)didReceiveNotification:(UNNotification *)notification { NSLog(@"notification---------%@",notification); } //用戶交互時觸發 - (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption option))completion { NSLog(@"response----------%@",response); } @end
6-4:模板使用
//支持完全自定義UI的通知 -(void)supportCustomUILocationNotification { //創建交互按鈕 UNNotificationAction *action = [UNNotificationAction actionWithIdentifier:@"action" title:@"自定義的Action" options:UNNotificationActionOptionNone]; //創建通知模板 //"myNotificationCategory"要與plist中配置的保持一樣 UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategory" actions:@[action] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; //通知內容類 UNMutableNotificationContent *content = [UNMutableNotificationContent new]; //設置通知請求發送時APP圖標上顯示的數字 content.badge = @1; //設置通知的內容 content.body = @"iOS10新通知內容,普通通知,歡迎哥來了"; //設置通知提示音 content.sound = [UNNotificationSound defaultSound]; //設置通知的副標題 content.subtitle = @"這是通知副標題"; //設置通知的標題 content.title = @"這是通知標題"; //設置從通知激活App時的lanunchImage圖片 content.launchImageName = @"lun"; //設置通知模板 //categoryIdentifier要與上面創建category的標識保持一致 content.categoryIdentifier = @"myNotificationCategory"; [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]]; //設置觸發器 //計時器觸發器:5s后執行 UNTimeIntervalNotificationTrigger *timrTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //設置通知請求 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"UNNotificationCustomUIH" content:content trigger:timrTrigger]; //添加通知請求 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@""); } }]; }

7、重寫媒體按鈕
#pragma mark - 重寫媒體按鈕 //重寫媒體按鈕的frame - (CGRect)mediaPlayPauseButtonFrame { return CGRectMake(70, 20, 100, 100); } //重寫媒體按鈕的顏色 - (UIColor *)mediaPlayPauseButtonTintColor { return [UIColor yellowColor]; } //重寫媒體按鈕類型 - (UNNotificationContentExtensionMediaPlayPauseButtonType)mediaPlayPauseButtonType { return UNNotificationContentExtensionMediaPlayPauseButtonTypeDefault; } //接收媒體按鈕播放事件 -(void)mediaPlay { NSLog(@"mediaPlay---------------開始播放"); } //接收媒體按鈕暫停事件 -(void)mediaPause { NSLog(@"mediaPause---------------暫停播放");

8、通知的代理方法
UserNotification框架對於通知的回調處理,是通過UNNotificationCenterDelegate協議來實現的。代理方法如下:
#pragma mark - UNUserNotificationCenterDelegate /* 僅當應用程序在前台時,才會調用該方法。 如果未實現該方法或未及時調用該處理程序,則不會顯示該通知。 應用程序可以選擇將通知顯示為聲音,徽章,警報和/或顯示在通知列表中。 該決定應基於通知中的信息是否對用戶可見。 */ - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { NSLog(@"------------當前應用在前台,收到了通知消息----------------"); completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); } /* 當接收到通知后,在用戶點擊通知激活應用程序時調用這個方法,無論是在前台還是后台 */ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler { NSLog(@"------------當前應用無論是在前台還是后台,收到了通知消息,用戶點擊該消息----------------"); completionHandler(); }
2019-11-02 23:24:47.618298+0800 本地推送[1765:86678] 2019-11-02 23:24:52.636497+0800 本地推送[1765:86538] ------------當前應用在前台,收到了通知消息---------------- 2019-11-02 23:25:21.748096+0800 本地推送[1765:86538] ------------當前應用無論是在前台還是后台,收到了通知消息,用戶點擊該消息----------------
