介紹
這個(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.framework
和UserNotificationsUI.framework
引入頭文件
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.m
、info.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.h
、NotificationViewController.m
积暖、MainInterface.storyboard
和info.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)示其高度是其寬度的一半