iOS10中涯塔,通知被整合進(jìn)了UserNotification框架鹤啡,用起來更加靈活了惯驼。之前只能簡(jiǎn)單的定義標(biāo)題递瑰,內(nèi)容類似醬祟牲。。抖部。牛逼了之后呢??
- 支持自定義音效和啟動(dòng)圖
- 可以向內(nèi)容中添加自定義附件说贝,比如音視頻
- 根據(jù)延遲時(shí)間,自定義時(shí)間慎颗,地理位置進(jìn)行設(shè)置
- 添加action
- 自定義界面
厲害嗎
一乡恕、UserNotification中的常用類
- UNNotificationCenter:?jiǎn)卫悾ㄖ淖?cè)俯萎,添加傲宜,請(qǐng)求。讯屈。蛋哭。
- UNNotificationContent:封裝通知的具體內(nèi)容
- UNNotificationTrigger:通知觸發(fā)器,具體自定義涮母。子類包括UNTimeInervalNotificationTrigger計(jì)時(shí)通知觸發(fā)器谆趾,UNCalendarNotificationTrigger周期通知觸發(fā)器,
UNLocationNotificationTrigger地域通知觸發(fā)器 - UNNotificationCenterDelegate:監(jiān)聽通知狀態(tài)
- UNNotificationCategory:通知模版叛本,可以對(duì)action進(jìn)行整合
- UNNotificationAction:用于定義通知模版中的用戶交互
- UNNotificationAttachment:可以添加媒體附件
- UNNotificationSettings:通知相關(guān)設(shè)置
- UNNotificationRequest:通知請(qǐng)求類沪蓬,整合通知內(nèi)容和觸發(fā)方式
- UNNotificationResponse:通知回執(zhí)
- UNNotification:通知對(duì)象,封裝通知請(qǐng)求
- UNNotificationSound:通知音效
二来候、通知注冊(cè)
引入頭文件#import <UserNotifications/UserNotifications.h>
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
//權(quán)限是否成功
if (granted) {
//權(quán)限申請(qǐng)成功跷叉,進(jìn)行代理的設(shè)置
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
}
}];
三、創(chuàng)建通知內(nèi)容
//通知內(nèi)容設(shè)置
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init];
content.title = @"我是標(biāo)題";
content.subtitle = @"我是副標(biāo)題";
content.body = @"我是內(nèi)容";
content.sound = [UNNotificationSound defaultSound];
content.badge = @1;
content.launchImageName = @"xcode";
//設(shè)置推送時(shí)間或周期
NSDateComponents *components = [[NSDateComponents alloc]init];
components.hour = @"9";
components.minute = @"28";
//請(qǐng)求通知
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LOCALNOTIFICATION_iOS10" content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"請(qǐng)檢查設(shè)置" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancelAction];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}
}];
四、觸發(fā)方式
1.UNTimeIntervalNotificationTrigger 設(shè)置一段時(shí)間后發(fā)送通知
@interface UNTimeIntervalNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly) NSTimeInterval timeInterval;
+ (instancetype)triggerWithTimeInterval:(NSTimeInterval)timeInterval repeats:(BOOL)repeats;
- (nullable NSDate *)nextTriggerDate;
@end
2.UNCalendarNotificationTrigger 設(shè)置某個(gè)時(shí)間點(diǎn)觸發(fā)
@interface UNCalendarNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDateComponents *dateComponents;
// The next date is calculated using matching date components.
+ (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)repeats;
- (nullable NSDate *)nextTriggerDate;
@end
3.UNLocationNotificationTrigger 設(shè)置進(jìn)入某一區(qū)域時(shí)觸發(fā)
@interface UNLocationNotificationTrigger : UNNotificationTrigger
@property (NS_NONATOMIC_IOSONLY, readonly, copy) CLRegion *region;
+ (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)repeats __WATCHOS_PROHIBITED;
@end
五云挟、添加內(nèi)容附件
內(nèi)容附件可以是圖片梆砸,音頻,視頻园欣,由UNNotificationAttachment
負(fù)責(zé)封裝帖世,賦值給UNMutableNotificationContent
類的attachments
屬性。
UNNotificationAttachment *attach = [UNNotificationAttachment attachmentWithIdentifier:@"LOCALNOTIFICATION_imageAttach" URL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"xcode" ofType:@"png"]] options:nil error:nil];
content.attachments = @[attach];
??UNNotificationContent的附件雖然是一個(gè)數(shù)組沸枯,但是系統(tǒng)的通知模板只能展示其中的第一個(gè)附件日矫,設(shè)置多個(gè)附件也不會(huì)有額外的效果,但是如果開發(fā)者進(jìn)行UI自定義绑榴,則此數(shù)組就可以派上用場(chǎng)了哪轿。
六、定義通知模版UNNotificationCategory
1.添加輸入框
//1.添加輸入框
UNTextInputNotificationAction *action = [UNTextInputNotificationAction actionWithIdentifier:@"UN_TextInputNotification_Action" title:@"title" options:UNNotificationActionOptionAuthenticationRequired textInputButtonTitle:@"ButtonTitle" textInputPlaceholder:@"PlaceHolder"];
//2.加入通知模版
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"UN_TextInputNotification_Action" actions:@[action] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
//3.設(shè)置為content的屬性
content.categoryIdentifier = @"UN_TextInputNotification_Action";
//4.將模版加入center
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
2.添加用戶交互
//添加活動(dòng)標(biāo)題(最多可添加4個(gè))
UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"解鎖" options:UNNotificationActionOptionAuthenticationRequired];
UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"取消" options:UNNotificationActionOptionDestructive];
UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"進(jìn)入前臺(tái)" options:UNNotificationActionOptionForeground];
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"LOCALNOTIFICATION_Category" actions:@[action1,action2,action3] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
content.categoryIdentifier = @"LOCALNOTIFICATION_Category";
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
七翔怎、通知回調(diào)處理
遵循協(xié)議<UNUserNotificationCenterDelegate>
實(shí)現(xiàn)代理方法
#pragma mark - UNNotificationCenterDelegate
//是否在應(yīng)用內(nèi)展示通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
//展示
completionHandler(UNNotificationPresentationOptionBadge|
UNNotificationPresentationOptionSound|
UNNotificationPresentationOptionAlert);
//不展示
//completionHandler(UNNotificationActionOptionNone);
}
//處理用戶與推送的交互
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
//根據(jù)類別標(biāo)識(shí)符
if ([response.notification.request.content.categoryIdentifier isEqualToString:@"LOCALNOTIFICATION_Category"]) {
[self handleWithResponse:response];
}
completionHandler();
}
-(void)handleWithResponse:(UNNotificationResponse *)response
{
NSString *actionIdentifier = response.actionIdentifier;
if ([actionIdentifier isEqualToString:@"UN_TextInputNotification_Action"]) {
UNTextInputNotificationResponse *input = (UNTextInputNotificationResponse *)response;
NSLog(@"%@",input.userText);
}else if ([actionIdentifier isEqualToString:@"action2"]){
NSLog(@"取消");
}else if ([actionIdentifier isEqualToString:@"action3"]){
NSLog(@"進(jìn)入前臺(tái)");
}
}
八窃诉、自定義模版
1.新建擴(kuò)展Notification Content Extension
file -> new -> target -> NotificationContent
創(chuàng)建完成后,工程中多了一個(gè)Notification Content的擴(kuò)展姓惑,自帶storyboard和plist文件褐奴。
2.配置plist文件
- UNNotificationExtensionCategory:設(shè)置模板的categoryId,用于與UNNotificationContent對(duì)應(yīng)于毙。
- UNNotificationExtensionInitialContentSizeRatio:設(shè)置自定義通知界面的高度與寬度的比敦冬,寬度為固定寬度,在不同設(shè)備上有差別唯沮,開發(fā)者需要根據(jù)寬度計(jì)算出高度進(jìn)行設(shè)置脖旱,系統(tǒng)根據(jù)這個(gè)比值來計(jì)算通知界面的高度。
- UNNotificationExtensionDefaultContentHidden:是有隱藏系統(tǒng)默認(rèn)的通知界面介蛉。
3.布局UI
UI布局在.m文件中進(jìn)行
- (void)didReceiveNotification:(UNNotification *)notification
{
self.label.text = notification.request.content.body;
self.subTitleLabel.text = notification.request.content.subtitle;
self.titleLabel.text = notification.request.content.title;
UNNotificationAttachment *attachment = notification.request.content.attachments.firstObject;
if (attachment.URL.startAccessingSecurityScopedResource) {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:attachment.URL.path];
// 壓縮避免圖片過大展示不全
NSData *imageData = UIImageJPEGRepresentation(img, 1.0);
UIImage *resultImage = [[UIImage alloc] initWithData:imageData];
self.imgView.image = resultImage;
[attachment.URL stopAccessingSecurityScopedResource];
}
}
??自定義模版上可以添加任何控件萌庆,但是無法進(jìn)行用戶交互,唯一可以進(jìn)行用戶交互的方式是通過協(xié)議中的媒體按鈕及其回調(diào)方法币旧。
九践险、移除本地推送
//移除將要推送的
- (void)removePendingNotificationRequestsWithIdentifiers:(NSArray<NSString *> *)identifiers;
- (void)removeAllPendingNotificationRequests;
//移除已經(jīng)推送的
- (void)removeDeliveredNotificationsWithIdentifiers:(NSArray<NSString *> *)identifiers;
- (void)removeAllDeliveredNotifications;