iOS10通知及通知拓展Extension使用詳解(附Demo)

來源:互聯網
上載者:User

標籤:ant   task   javascrip   for   判斷   ref   nim   nes   isa   

1.1-iOS10拓展簡介

1.2-iOS10通知使用

1.3-iOS10通知拓展Extension使用

1.4-效果示範

  • 如果對開發有興趣的可以來黑馬學習iOS開發:黑馬程式員

  • 原始碼:代碼下載

1.1-iOS10拓展簡介
  • iOS10系統最大的一個亮點就是增加了系統應用的拓展功能Extension

    • Extension功能可以理解為自訂系統介面
  • 本小節我們就以自訂系統通知介面來學習一下Extension的使用

    • 其他功能的Extension我們不可能逐一講解,希望大家能夠在理解的基礎上,做到舉一反三

1.2-iOS10通知使用
  • iOS10之後,為了對自訂通知介面拓展Notification Content的支援,iOS系統推出了新的架構<UserNotifications>

    • 通知的使用思路和步驟不變,只是API發生了變化,並且系統全部會有提示,我們只需要根據系統提示修改一下即可
  • 1.請求授權及添加分類

#import "AppDelegate.h"//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:.}@end
  • 2.發送通知(含分類互動按鈕)
#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"]];}
1.3-iOS10通知拓展Extension使用
  • 1.添加通知拓展

  • 2.通知的拓展Extension實際上相當於在當前的應用程式重新添加一個應用程式,工程會添加對應的代碼檔案夾和target

  • 3.預設拓展控制器只有一個Label,我們可以在這裡自訂我們的控制器介面

  • 4.也可以載入通知中推送的資料

  • 5.配置plist檔案
    • 預設情況下應用程式是不會載入拓展介面的,需要配置plist檔案,關閉系統預設通知介面

  • 6.運行
    • 啟動並執行話不需要選擇Extension的target,直接選擇應用程式的target即可

1.4-效果示範

iOS10通知及通知拓展Extension使用詳解(附Demo)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.