iOS10 新通知功能UserNotifications應(yīng)用

介紹

這個(gè)demo可以幫助你快速的了解iOS10中引入的新通知功能抽莱,該功能向用戶呈現(xiàn)了強(qiáng)大而靈活的通知驾讲。本文將會(huì)介紹如何給通知附加媒體內(nèi)容腔彰、自定義通知UI等蝴簇。

背景

iOS10為開發(fā)人員提供了更強(qiáng)大燎斩、更靈活的本地和遠(yuǎn)程通知虱歪,它引進(jìn)了兩個(gè)新的框架

  • UserNotifications.framework
  • UserNotificationsUI.framework

新的功能

  • 通知支持視頻、音頻栅表、圖片
  • App在前臺(tái)仍然可以顯示通知
  • 給通知添加action操作
  • 可以快速回復(fù)文本
  • 支持gif圖
  • 自定義通知的界面

代碼

我們基于iOS10的新的通知功能創(chuàng)建一個(gè)本地通知
在Xcode中笋鄙,到工程設(shè)置Build Phases -> Link Binary With Libraries中添加UserNotifications.frameworkUserNotificationsUI.framework

添加庫截圖.png

引入頭文件

import <UserNotifications/UserNotifications.h> 

當(dāng)應(yīng)用處于前臺(tái)時(shí)獲取通知
首先需要遵守UNUserNotificationCenterDelegate協(xié)議,實(shí)現(xiàn)userNotificationCenter:willPresentNotification:withCompletionHandler:代理方法

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
{
    completionHandler(UNNotificationPresentationOptionAlert);
}

注冊(cè)通知服務(wù)
無論是遠(yuǎn)程通知還是本地通知都必須先注冊(cè)通知服務(wù)怪瓶,定義如下屬性

@property(strong,nonatomic) UNUserNotificationCenter* notiCenter;

初始化這個(gè)屬性

  _notiCenter = [UNUserNotificationCenter currentNotificationCenter];
    _notiCenter.delegate=self;
    [_notiCenter  requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        //Enable or disable features based on authorization.
        if(granted)
        {
            [_notiCenter setDelegate:self];
                [self generateTimerBasedNotification];
                [self generateLocationBasedNotification];
                // _categoryActionSet has collected all the actions from different kind of notifications and adding it to notification Center
                [[self notiCenter] setNotificationCategories:_categoryActionSet];
        }
    }];

可以通過iOS10UNUserNotificationCenter的API獲取到通知設(shè)置的屬性

// Read the notification setting, set by user
    [_notiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        
        if(settings.soundSetting==UNNotificationSettingEnabled)
        {
            NSLog(@"Sound Notification is Enabled");
        }
        else
        {
            NSLog(@"Sound Notification is Disabled");
        }
        if(settings.alertSetting==UNNotificationSettingEnabled)
        {
            NSLog(@"Alert Notification is Enabled");
        }
        else
        {
            NSLog(@"Alert Notification is Disabled");
        }
        if(settings.badgeSetting==UNNotificationSettingEnabled)
        {
            NSLog(@"Badge is Enabled");
        }
        else
        {
            NSLog(@"Badge is Disabled");
        }
    }];

iOS10中新添加了兩個(gè)擴(kuò)展

  • 通知服務(wù)(Notification Service)
  • 通知內(nèi)容(Notification Content)

Notification Service
它是運(yùn)行在后臺(tái)以用來下載遠(yuǎn)程通知中指定的URL,或者將遠(yuǎn)程通知的內(nèi)容在展示給用戶之前進(jìn)行替換
在file->New->Target選擇Notification Service Extension
添加完target后將會(huì)創(chuàng)建NotificationService.h萧落、NotificationService.minfo.plist三個(gè)文件
NotificationService類派生自UNNotificationServiceExtension,這個(gè)基類只有兩個(gè)方法找岖,而且通知服務(wù)僅用于遠(yuǎn)程通知

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *contentToDeliver))contentHandler;

此方法用于下載遠(yuǎn)程通知中的URL內(nèi)容以展示給用戶

- (void)serviceExtensionTimeWillExpire;

如果程序無法在給定的時(shí)間內(nèi)(從設(shè)備接受到遠(yuǎn)程通知到傳遞給用戶的時(shí)間)完成下載陨倡,那么此方法為備用方案,
一旦設(shè)備接受到遠(yuǎn)程通知并且將其展示給用戶之前许布,系統(tǒng)將運(yùn)行該服務(wù)擴(kuò)展兴革,首先,系統(tǒng)將會(huì)調(diào)用didReceiveNotificationRequest蜜唾,在這里可以從UNNotificationRequest中獲取到通知的數(shù)據(jù)杂曲,并獲取到媒體的URL開始下載。如果再給定的時(shí)間下載失敗或者下載沒有完成袁余,系統(tǒng)將會(huì)調(diào)用serviceExtensionTimeWillExpire告訴我們分配給下載內(nèi)容的時(shí)間將要過去擎勘,在這里可以有一些代替的解決方案,我們可以替換為本地的圖片泌霍、視頻货抄、音頻等。
Notification Content
在file->New->Target選擇Notification Content
此內(nèi)容擴(kuò)展可以幫助我們添加自定義的視圖朱转,以及處理用戶對(duì)通知的操作.
添加了target之后將會(huì)創(chuàng)建NotificationViewController.hNotificationViewController.m积暖、MainInterface.storyboardinfo.plist藤为。
使用MainInterface.storyboard自定義我們的通知視圖,在Notification View Controller Scene拖拽我們想要的通知樣式
當(dāng)用戶點(diǎn)擊任何操作按鈕時(shí)夺刑,系統(tǒng)都會(huì)調(diào)用didReceiveNotificationResponse委托方法

帶有媒體文件的通知

將圖片添加到通知
使用UNMutableNotificationContent類可以像通知中添加許多內(nèi)容缅疟、
在本地通知中,我們可以將圖片遍愿,音頻或者視頻的路徑添加到UNMutableNotificationContent.attachments

    UNMutableNotificationContent *notificationcontent = [[UNMutableNotificationContent alloc] init];
    notificationcontent.title = [NSString localizedUserNotificationStringForKey:@"New Arrivals" arguments:nil];
    notificationcontent.body = [NSString localizedUserNotificationStringForKey:@"New arrival of Your favourite products!"
                                                         arguments:nil];
    notificationcontent.sound = [UNNotificationSound defaultSound];
    // category identitifer should be unique and  should match with identitifer of its corresponding UNNotificationCategory
    notificationcontent.categoryIdentifier=@"com.mcoe.notificationcategory.timerbased";
    NSError *error=nil;
    // reading image from bundle and copying it to document directory.
    NSURL *fileFromBundle =[[NSBundle mainBundle] URLForResource:@"psc" withExtension:@"png"];
    // Destination URL
    NSURL *url = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:@"psc.png"];
    NSError *error1;
    // copying from bundle to document directory
     [[NSFileManager defaultManager]copyItemAtURL:fileFromBundle toURL:url error:&error1];
    // creating attachment with image url
    UNNotificationAttachment *image_attachment=[UNNotificationAttachment attachmentWithIdentifier:@"com.mcoe.notificationcategory.timerbased" URL:url options:nil error:&error];
    notificationcontent.attachments=[NSArray arrayWithObject:image_attachment];
    notificationcontent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

向通知添加操作

主要有3種操作

  • Default Actions - 默認(rèn)操作是用戶從通知打開應(yīng)用
  • Custom Actions - 可以直接從通知本身執(zhí)行存淫,無需啟動(dòng)應(yīng)用
  • Dismiss Actions - 關(guān)閉操作
 // Adding custom actions
    
    UNNotificationAction *checkoutAction = [UNNotificationAction actionWithIdentifier:@"com.mcoe.notificationcategory.timerbased.yes"
                                                                              title:@"Check out"
                                                                            options:UNNotificationActionOptionForeground];
    UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"com.mcoe.notificationcategory.timerbased.no"
                                                                               title:@"Decline"
                                                                             options:UNNotificationActionOptionDestructive];
    UNNotificationAction *laterAction = [UNNotificationAction actionWithIdentifier:@"com.mcoe.notificationcategory.timerbased.dismiss"
                                                                              title:@"Later"
                                                                            options:UNNotificationActionOptionDestructive];
    NSArray *NotificationActions = @[ checkoutAction, declineAction, laterAction ];
    
    // categoryWithIdentifier should match with the value of UNNotificationExtensionCategory in info.plist of its corresponding content extension
    UNNotificationCategory *TimernotificationCategory=[UNNotificationCategory categoryWithIdentifier:@"com.mcoe.notificationcategory.timerbased" actions:NotificationActions intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
    
    
    
    [_categoryActionSet addObject:TimernotificationCategory];

計(jì)劃通知

本地通知可以通過三種方式觸發(fā)

  • 時(shí)間間隔
  • 日歷時(shí)間
  • 位置信息

時(shí)間間隔

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger 
                                                             triggerWithTimeInterval:3.f repeats:NO];

位置信息

    //Creating region object and generating Notification trigger object out of it.
    CLLocationCoordinate2D officeArea = CLLocationCoordinate2DMake(12.970540,80.251060);
    CLCircularRegion* officeRegion = [[CLCircularRegion alloc] initWithCenter:officeArea
                                                                       radius:10 identifier:@"My Office Bay"];
    
    officeRegion.notifyOnEntry = YES;
    officeRegion.notifyOnExit = YES;
    UNLocationNotificationTrigger* locationTrigger = [UNLocationNotificationTrigger
                                                      triggerWithRegion:officeRegion repeats:YES];

創(chuàng)建請(qǐng)求對(duì)象并添加到通知中心

  UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"com.mcoe.notificationcategory.timerbased"
                                      
                                                                          content:notificationcontent trigger:timerbasedtrigger];
    
    [_notiCenter addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"added timer based NotificationRequest suceessfully!");
        }
    }];

注意

  • 我們分配給UNNotificationCategory對(duì)象的 category identifier 和通知內(nèi)容擴(kuò)展的info.plist中的UNNotificationExtensionCategory標(biāo)示符名稱應(yīng)該相同
  • 由于我們可以向項(xiàng)目中添加多個(gè)擴(kuò)展,系統(tǒng)使用接受到的通知中的類別標(biāo)示符名稱找到其對(duì)應(yīng)的擴(kuò)展代碼以調(diào)用其委托方法
  • UNNotificationExtensionInitialContentSizeRatio在通知內(nèi)容擴(kuò)展的info.plist中指示自定義視圖的寬高比沼填,其范圍在0到1之間桅咆。1標(biāo)示自定義界面高度等于其寬度,0標(biāo)示其高度是其寬度的一半
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坞笙,一起剝皮案震驚了整個(gè)濱河市岩饼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌薛夜,老刑警劉巖籍茧,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異梯澜,居然都是意外死亡寞冯,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吮龄,“玉大人俭茧,你說我怎么就攤上這事∶” “怎么了恢恼?”我有些...
    開封第一講書人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長胰默。 經(jīng)常有香客問我场斑,道長,這世上最難降的妖魔是什么牵署? 我笑而不...
    開封第一講書人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任漏隐,我火速辦了婚禮,結(jié)果婚禮上奴迅,老公的妹妹穿的比我還像新娘青责。我一直安慰自己,他們只是感情好取具,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開白布脖隶。 她就那樣靜靜地躺著,像睡著了一般暇检。 火紅的嫁衣襯著肌膚如雪产阱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,578評(píng)論 1 305
  • 那天块仆,我揣著相機(jī)與錄音构蹬,去河邊找鬼。 笑死悔据,一個(gè)胖子當(dāng)著我的面吹牛庄敛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播科汗,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼藻烤,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了肛捍?” 一聲冷哼從身側(cè)響起隐绵,我...
    開封第一講書人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拙毫,沒想到半個(gè)月后依许,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡缀蹄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年峭跳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了膘婶。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蛀醉,死狀恐怖悬襟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拯刁,我是刑警寧澤脊岳,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站垛玻,受9級(jí)特大地震影響割捅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜帚桩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一亿驾、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧账嚎,春花似錦莫瞬、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至召锈,卻和暖如春檩小,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背烟勋。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留筐付,地道東北人卵惦。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像瓦戚,于是被迫代替她去往敵國和親沮尿。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容