iOS10中的UserNotification--本地推送

iOS10中涯塔,通知被整合進(jìn)了UserNotification框架鹤啡,用起來更加靈活了惯驼。之前只能簡(jiǎn)單的定義標(biāo)題递瑰,內(nèi)容類似醬祟牲。。抖部。牛逼了之后呢??

  • 支持自定義音效和啟動(dòng)圖
  • 可以向內(nèi)容中添加自定義附件说贝,比如音視頻
  • 根據(jù)延遲時(shí)間,自定義時(shí)間慎颗,地理位置進(jìn)行設(shè)置
  • 添加action
  • 自定義界面

厲害嗎

一乡恕、UserNotification中的常用類
  1. UNNotificationCenter:?jiǎn)卫悾ㄖ淖?cè)俯萎,添加傲宜,請(qǐng)求。讯屈。蛋哭。
  2. UNNotificationContent:封裝通知的具體內(nèi)容
  3. UNNotificationTrigger:通知觸發(fā)器,具體自定義涮母。子類包括UNTimeInervalNotificationTrigger計(jì)時(shí)通知觸發(fā)器谆趾,UNCalendarNotificationTrigger周期通知觸發(fā)器,
    UNLocationNotificationTrigger地域通知觸發(fā)器
  4. UNNotificationCenterDelegate:監(jiān)聽通知狀態(tài)
  5. UNNotificationCategory:通知模版叛本,可以對(duì)action進(jìn)行整合
  6. UNNotificationAction:用于定義通知模版中的用戶交互
  7. UNNotificationAttachment:可以添加媒體附件
  8. UNNotificationSettings:通知相關(guān)設(shè)置
  9. UNNotificationRequest:通知請(qǐng)求類沪蓬,整合通知內(nèi)容和觸發(fā)方式
  10. UNNotificationResponse:通知回執(zhí)
  11. UNNotification:通知對(duì)象,封裝通知請(qǐng)求
  12. 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];
    }

}];
最基本設(shè)置.png
四、觸發(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)了哪轿。


附件格式大小要求.png
添加附件內(nèi)容效果圖.png
六、定義通知模版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]];
添加輸入框效果圖.png
七翔怎、通知回調(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)的通知界面介蛉。
plist配置.png

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)方法币旧。


自定義模版效果圖.png
九践险、移除本地推送
//移除將要推送的
- (void)removePendingNotificationRequestsWithIdentifiers:(NSArray<NSString *> *)identifiers;
- (void)removeAllPendingNotificationRequests;
//移除已經(jīng)推送的
- (void)removeDeliveredNotificationsWithIdentifiers:(NSArray<NSString *> *)identifiers;
- (void)removeAllDeliveredNotifications;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市吹菱,隨后出現(xiàn)的幾起案子巍虫,更是在濱河造成了極大的恐慌,老刑警劉巖鳍刷,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件占遥,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡输瓜,警方通過查閱死者的電腦和手機(jī)瓦胎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門芬萍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人搔啊,你說我怎么就攤上這事柬祠。” “怎么了负芋?”我有些...
    開封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵瓶盛,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我示罗,道長(zhǎng),這世上最難降的妖魔是什么芝硬? 我笑而不...
    開封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任蚜点,我火速辦了婚禮,結(jié)果婚禮上拌阴,老公的妹妹穿的比我還像新娘绍绘。我一直安慰自己,他們只是感情好迟赃,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開白布陪拘。 她就那樣靜靜地躺著,像睡著了一般纤壁。 火紅的嫁衣襯著肌膚如雪左刽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天酌媒,我揣著相機(jī)與錄音欠痴,去河邊找鬼。 笑死秒咨,一個(gè)胖子當(dāng)著我的面吹牛喇辽,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播雨席,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼菩咨,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了陡厘?” 一聲冷哼從身側(cè)響起抽米,我...
    開封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤走哺,失蹤者是張志新(化名)和其女友劉穎画机,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哲嘲,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡罢低,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年查辩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了胖笛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡宜岛,死狀恐怖长踊,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情萍倡,我是刑警寧澤身弊,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站列敲,受9級(jí)特大地震影響阱佛,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜戴而,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一凑术、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧所意,春花似錦淮逊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至秧耗,卻和暖如春备籽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背绣版。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工胶台, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人杂抽。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓诈唬,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親缩麸。 傳聞我的和親對(duì)象是個(gè)殘疾皇子铸磅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

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