iOS 10 添加本地推送(Local Notification)

前言
iOS 10 中廢棄了 UILocalNotification( UIKit Framework) 這個(gè)類,采用了全新的 UserNotifications Framework 來(lái)推送通知列赎,從此推送通知也有了自己的標(biāo)簽 UN(這待遇真是沒別人了)魏保,以及對(duì)推送功能的一系列增強(qiáng)改進(jìn)(兩個(gè) extension 和 界面的體驗(yàn)優(yōu)化),簡(jiǎn)直是蘋果的親兒子,因此推送這部分功能也成為開發(fā)中的重點(diǎn)。

本文主要查看了 iOS 10 的相關(guān)文檔脂信,整理出了在 iOS 10 下的本地推送通知,由于都是代碼透硝,就不多做講解吉嚣,直接看代碼及注釋,有問題留言討論哦蹬铺。

新的推送注冊(cè)機(jī)制
注冊(cè)通知(Appdelegate.m):


#import <UserNotifications/UserNotifications.h>
#import "AppDelegate.h"
@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // 使用 UNUserNotificationCenter 來(lái)管理通知
   UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
   //監(jiān)聽回調(diào)事件
   center.delegate = self;
   
   //iOS 10 使用以下方法注冊(cè),才能得到授權(quán)
   [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                         completionHandler:^(BOOL granted, NSError * _Nullable error) {
                             // Enable or disable features based on authorization.
                         }];
   
   //獲取當(dāng)前的通知設(shè)置秉撇,UNNotificationSettings 是只讀對(duì)象甜攀,不能直接修改秋泄,只能通過(guò)以下方法獲取
   [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
       
   }];
   return YES;
}

#pragma mark - UNUserNotificationCenterDelegate
//在展示通知前進(jìn)行處理,即有機(jī)會(huì)在展示通知前再修改通知內(nèi)容规阀。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
   //1. 處理通知
   
   //2. 處理完成后條用 completionHandler 恒序,用于指示在前臺(tái)顯示通知的形式
   completionHandler(UNNotificationPresentationOptionAlert);
}
@end

推送本地通知

//使用 UNNotification 本地通知
+(void)registerNotification:(NSInteger )alerTime{
    
    // 使用 UNUserNotificationCenter 來(lái)管理通知
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    
    //需創(chuàng)建一個(gè)包含待通知內(nèi)容的 UNMutableNotificationContent 對(duì)象,注意不是 UNNotificationContent ,此對(duì)象為不可變對(duì)象谁撼。
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello_message_body"
                                                         arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    
    // 在 alertTime 后推送本地推送
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:alerTime repeats:NO];

    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                          content:content trigger:trigger];
    
    //添加推送成功后的處理歧胁!
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    }];
}

iOS 10 以前本地推送通知:

+ (void)registerLocalNotificationInOldWay:(NSInteger)alertTime {
    // ios8后,需要添加這個(gè)注冊(cè)厉碟,才能得到授權(quán)
    //    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    //        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    //        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
    //                                                                                 categories:nil];
    //        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    //        // 通知重復(fù)提示的單位喊巍,可以是天、周箍鼓、月
    //    }
    
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 設(shè)置觸發(fā)通知的時(shí)間
    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
    NSLog(@"fireDate=%@",fireDate);
    
    notification.fireDate = fireDate;
    // 時(shí)區(qū)
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 設(shè)置重復(fù)的間隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知內(nèi)容
    notification.alertBody =  @"該起床了...";
    notification.applicationIconBadgeNumber = 1;
    // 通知被觸發(fā)時(shí)播放的聲音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知參數(shù)
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"開始學(xué)習(xí)iOS開發(fā)了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后崭参,需要添加這個(gè)注冊(cè),才能得到授權(quán)
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重復(fù)提示的單位款咖,可以是天何暮、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重復(fù)提示的單位铐殃,可以是天海洼、周、月
        notification.repeatInterval = NSDayCalendarUnit;
    }
    
    // 執(zhí)行通知注冊(cè)
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末富腊,一起剝皮案震驚了整個(gè)濱河市坏逢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蟹肘,老刑警劉巖词疼,帶你破解...
    沈念sama閱讀 217,185評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異帘腹,居然都是意外死亡贰盗,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門阳欲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)舵盈,“玉大人,你說(shuō)我怎么就攤上這事球化』嗤恚” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵筒愚,是天一觀的道長(zhǎng)赴蝇。 經(jīng)常有香客問我,道長(zhǎng)巢掺,這世上最難降的妖魔是什么句伶? 我笑而不...
    開封第一講書人閱讀 58,339評(píng)論 1 293
  • 正文 為了忘掉前任劲蜻,我火速辦了婚禮,結(jié)果婚禮上考余,老公的妹妹穿的比我還像新娘先嬉。我一直安慰自己,他們只是感情好楚堤,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評(píng)論 6 391
  • 文/花漫 我一把揭開白布疫蔓。 她就那樣靜靜地躺著,像睡著了一般身冬。 火紅的嫁衣襯著肌膚如雪衅胀。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評(píng)論 1 301
  • 那天吏恭,我揣著相機(jī)與錄音拗小,去河邊找鬼。 笑死樱哼,一個(gè)胖子當(dāng)著我的面吹牛哀九,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播搅幅,決...
    沈念sama閱讀 40,130評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼阅束,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了茄唐?” 一聲冷哼從身側(cè)響起息裸,我...
    開封第一講書人閱讀 38,985評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎沪编,沒想到半個(gè)月后呼盆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,420評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蚁廓,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評(píng)論 3 334
  • 正文 我和宋清朗相戀三年访圃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片相嵌。...
    茶點(diǎn)故事閱讀 39,779評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腿时,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出饭宾,到底是詐尸還是另有隱情批糟,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評(píng)論 5 345
  • 正文 年R本政府宣布看铆,位于F島的核電站徽鼎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜纬傲,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評(píng)論 3 328
  • 文/蒙蒙 一满败、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧叹括,春花似錦、人聲如沸宵荒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)报咳。三九已至侠讯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間暑刃,已是汗流浹背厢漩。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留岩臣,地道東北人溜嗜。 一個(gè)月前我還...
    沈念sama閱讀 47,876評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像架谎,于是被迫代替她去往敵國(guó)和親炸宵。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評(píng)論 2 354

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

  • WWDC session - Notifications 學(xué)習(xí)總結(jié)裹匙,如有不妥之處,望請(qǐng)指正???? pusher工具[...
    kurt_wang閱讀 5,004評(píng)論 12 28
  • 極光推送: 1.JPush當(dāng)前版本是1.8.2末秃,其SDK的開發(fā)除了正常的功能完善和擴(kuò)展外也緊隨蘋果官方的步伐概页,SD...
    Isspace閱讀 6,719評(píng)論 10 16
  • 一、簡(jiǎn)單介紹: iOS 10 中 通知 有了新的改變: 首先:第一個(gè)更新點(diǎn)就是:新加了一個(gè)獨(dú)立框架:UserN...
    藍(lán)白七七閱讀 947評(píng)論 1 4
  • 一下山蛔溃,淅淅瀝瀝的春雨绰沥,像是剛剛好讓我們可以在路邊的農(nóng)居歇腳。春意也就如此揮灑在這日漸蘇醒的草地和矮山中贺待。萬(wàn)物重生...
    Vitre閱讀 110評(píng)論 0 0
  • 首次就成功(高興得太早) 二次就失敗(總會(huì)失敗的) 但不可以放棄的第三次(怎么會(huì)一直失敗下去)
    王想W閱讀 561評(píng)論 10 14