1.1-iOS10拓展簡介
1.2-iOS10通知使用
1.3-iOS10通知拓展Extension使用
1.4-效果演示
如果對開發有興趣的可以來黑馬學習iOS開發:黑馬程序員
源代碼下載地址:Deme下載
iOS10系統最大的一個亮點就是增加了系統應用的拓展功能Extension
本小節我們就以自定義系統通知界面來學習一下Extension的使用
Extension我們不可能逐一講解,希望大家能夠在理解的基礎上,做到舉一反三
iOS10之后,為了對自定義通知界面拓展Notification Content的支持,iOS系統推出了新的框架<UserNotifications>
1.請求授權及添加分類
#import "AppDelegate.h"http://iOS10通知新框架#import <UserNotifications/UserNotifications.h>//iOS10 自定義通知界面#import <UserNotificationsUI/UserNotificationsUI.h>@interface AppDelegate ()<UNUserNotificationCenterDelegate>@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. //申請授權 //1.創建通知中心 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; //設置通知中心的代理(iOS10之后監聽通知的接收時間和交互按鈕的響應是通過代理來完成的) center.delegate = self; //2.通知中心設置分類 [center setNotificationCategories:[NSSet setWithObjects:[self createCatrgory], nil]]; //3.請求授權 /**UNAuthorizationOption UNAuthorizationOptionBadge = (1 << 0),紅色圓圈 UNAuthorizationOptionSound = (1 << 1),聲音 UNAuthorizationOptionAlert = (1 << 2),內容 UNAuthorizationOptionCarPlay = (1 << 3),車載通知 */ [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted == YES) { NSLog(@"授權成功"); } }]; return YES;}//當APP處于前臺的時候接收到通知- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPResentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{ //彈出一個網頁 UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 400, 500)]; webview.center = self.window.center; [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.itheima.com"]]]; [self.window addSubview:webview]; //彈出動畫 webview.alpha = 0; [UIView animateWithDuration:1 animations:^{ webview.alpha = 1; }];}#pragma mark - 創建通知分類(交互按鈕)- (UNNotificationCategory *)createCatrgory{ //文本交互(iOS10之后支持對通知的文本交互) /**options UNNotificationActionOptionAuthenticationRequired 用于文本 UNNotificationActionOptionForeground 前臺模式,進入APP UNNotificationActionOptionDestructive 銷毀模式,不進入APP */ UNTextInputNotificationAction *textInputAction = [UNTextInputNotificationAction actionWithIdentifier:@"textInputAction" title:@"請輸入信息" options:UNNotificationActionOptionAuthenticationRequired textInputButtonTitle:@"輸入" textInputPlaceholder:@"還有多少話要說……"]; //打開應用按鈕 UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"foreGround" title:@"打開" options:UNNotificationActionOptionForeground]; //不打開應用按鈕 UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"backGround" title:@"關閉" options:UNNotificationActionOptionDestructive]; //創建分類 /** Identifier:分類的標識符,通知可以添加不同類型的分類交互按鈕 actions:交互按鈕 intentIdentifiers:分類內部標識符 沒什么用 一般為空就行 options:通知的參數 UNNotificationCategoryOptionCustomDismissAction:自定義交互按鈕 UNNotificationCategoryOptionAllowInCarPlay:車載交互 */ UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"category" actions:@[textInputAction,action1,action2] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; return category;}//按鈕點擊事件- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{ //根據identifer判斷按鈕類型,如果是textInput則獲取輸入的文字 if ([response.actionIdentifier isEqualToString:@"textInputAction"]) { //獲取文本響應 UNTextInputNotificationResponse *textResponse = (UNTextInputNotificationResponse *)response; NSLog(@"輸入的內容為:%@",textResponse.userText); } //處理其他時間 NSLog(@"%@",response.actionIdentifier);}- (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end2.發送通知(含分類交互按鈕)#pragma mark - 發送本地通知- (IBAction)sendLocalNotification:(id)sender { //1.創建通知中心 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; //2.檢查當前用戶授權 [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { NSLog(@"當前授權狀態:%zd",[settings authorizationStatus]); //3.創建通知 UNMutableNotificationContent *notification = [[UNMutableNotificationContent alloc] init]; //3.1通知標題 notification.title = [NSString localizedUserNotificationStringForKey:@"傳智播客" arguments:nil]; //3.2小標題 notification.subtitle = @"hellow world"; //3.3通知內容 notification.body = @"歡迎來到黑馬程序員"; //3.4通知聲音 notification.sound = [UNNotificationSound defaultSound]; //3.5通知小圓圈數量 notification.badge = @2; //4.創建觸發器(相當于iOS9中通知觸發的時間) /**通知觸發器主要有三種 UNTimeIntervalNotificationTrigger 指定時間觸發 UNCalendarNotificationTrigger 指定日歷時間觸發 UNLocationNotificationTrigger 指定區域觸發 */ UNTimeIntervalNotificationTrigger * timeTrigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; //5.指定通知的分類 (1)identifer表示創建分類時的唯一標識符 (2)該代碼一定要在創建通知請求之前設置,否則無效 notification.categoryIdentifier = @"category"; //給通知添加附件(圖片 音樂 電影都可以) NSString *path = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"png"]; UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:[NSURL fileURLWithPath:path] options:nil error:nil]; notification.attachments = @[attachment]; //7.創建通知請求 /** Identifier:通知請求標識符,用于刪除或者查找通知 content:通知的內容 trigger:通知觸發器 */ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"localNotification" content:notification trigger:timeTrigger]; //8.通知中心發送通知請求 [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (error == nil) { NSLog(@"通知發送成功"); } else { NSLog(@"%@",error); } }]; }];}3.通知的移除#pragma mark - 移除所有通知- (IBAction)removeAllNotification:(id)sender { //1.創建通知中心 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; //2.刪除已經推送過得通知 [center removeAllDeliveredNotifications]; //3.刪除未推送的通知請求 [center removeAllPendingNotificationRequests];}#pragma mark - 移除指定通知- (IBAction)removeSingleNotification:(id)sender { //1.創建通知中心 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; //2.刪除指定identifer的已經發送的通知 [center removeDeliveredNotificationsWithIdentifiers:@[@"localNotification"]]; //3.刪除指定identifer未發送的同志請求 [center removeDeliveredNotificationsWithIdentifiers:@[@"localNotification"]];}




Extension的target,直接選擇應用程序的target即可

新聞熱點
疑難解答