iOS10本地推送實(shí)踐記錄(Objective-C)

首先感謝喵神活久見(jiàn)的重構(gòu) - iOS 10 UserNotifications 框架解析霜神WWDC2016 Session筆記 - iOS 10 推送Notification新特性员咽,文章對(duì)推送剖析的很徹底翎朱,本文僅僅是學(xué)習(xí)實(shí)踐過(guò)程中的筆記(還用的Objective-C)昂验。

發(fā)送通知

在一切開(kāi)始之前,一定要#import <UserNotifications/UserNotifications.h>瓢娜。因?yàn)閕OS10中,推送通知的相關(guān)功能提取到了這個(gè)新加入的框架视事。

然后监憎,就可以上代碼了~

    // 申請(qǐng)通知權(quán)限
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        
        // A Boolean value indicating whether authorization was granted. The value of this parameter is YES when authorization for the requested options was granted. The value is NO when authorization for one or more of the options is denied.
        if (granted) {
            
            // 1、創(chuàng)建通知內(nèi)容贸人,注:這里得用可變類型的UNMutableNotificationContent间景,否則內(nèi)容的屬性是只讀的
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            // 標(biāo)題
            content.title = @"柯梵通知";
            // 次標(biāo)題
            content.subtitle = @"柯梵辦公室通知";
            // 內(nèi)容
            content.body = @"柯梵科技是一家以人為本,具有強(qiáng)烈社會(huì)責(zé)任感的公司艺智。公司的最大愿景就是每個(gè)員工都能住上大房子拱燃,開(kāi)上好車,實(shí)現(xiàn)逆襲高富帥力惯、白富美的愿望。";
            
            self.badge++;
            // app顯示通知數(shù)量的角標(biāo)
            content.badge = @(self.badge);
            
            // 通知的提示聲音召嘶,這里用的默認(rèn)的聲音
            content.sound = [UNNotificationSound defaultSound];
            
            NSURL *imageUrl = [[NSBundle mainBundle] URLForResource:@"jianglai" withExtension:@"jpg"];
            UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"imageIndetifier" URL:imageUrl options:nil error:nil];
            
            // 附件 可以是音頻父晶、圖片、視頻 這里是一張圖片
            content.attachments = @[attachment];
            
            // 標(biāo)識(shí)符
            content.categoryIdentifier = @"categoryIndentifier";
            
            // 2弄跌、創(chuàng)建通知觸發(fā)
            /* 觸發(fā)器分三種:
             UNTimeIntervalNotificationTrigger : 在一定時(shí)間后觸發(fā)甲喝,如果設(shè)置重復(fù)的話,timeInterval不能小于60
             UNCalendarNotificationTrigger : 在某天某時(shí)觸發(fā)铛只,可重復(fù)
             UNLocationNotificationTrigger : 進(jìn)入或離開(kāi)某個(gè)地理區(qū)域時(shí)觸發(fā)
            */
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
            
            // 3埠胖、創(chuàng)建通知請(qǐng)求
            UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"KFGroupNotification" content:content trigger:trigger];
            
            // 4、將請(qǐng)求加入通知中心
            [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
                if (error == nil) {
                    NSLog(@"已成功加推送%@",notificationRequest.identifier);
                }
            }];
        }
        
    }];

這樣淳玩,發(fā)送通知的步驟就完成了直撤,回到手機(jī)桌面(不特別設(shè)置的話,應(yīng)用內(nèi)是不展示通知的)蜕着,5秒之后就可以收到一條通知了谋竖。如下圖(解鎖狀態(tài)和鎖屏狀態(tài)):


要注意的是红柱,一旦用戶拒絕了這個(gè)請(qǐng)求,再次調(diào)用該方法也不會(huì)再進(jìn)行彈窗蓖乘,想要應(yīng)用有機(jī)會(huì)接收到通知的話锤悄,用戶必須自行前往系統(tǒng)的設(shè)置中為你的應(yīng)用打開(kāi)通知,而這往往是不可能的嘉抒。因此零聚,在合適的時(shí)候彈出請(qǐng)求窗,在請(qǐng)求權(quán)限前預(yù)先進(jìn)行說(shuō)明些侍,而不是直接粗暴地在啟動(dòng)的時(shí)候就進(jìn)行彈窗隶症,會(huì)是更明智的選擇。

這里我和瞄神的觀點(diǎn)一致娩梨,所以在需要發(fā)送通知的地方才申請(qǐng)通知權(quán)限沿腰。

修改通知

修改內(nèi)容,增加一個(gè)新的通知請(qǐng)求到消息中心狈定,此請(qǐng)求和原來(lái)的標(biāo)識(shí)符一樣颂龙。

UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
......

UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:@"KFGroupNotification" content:content trigger:trigger];
            
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
       if (error == nil) {
           NSLog(@"已成功更新推送%@",notificationRequest.identifier);
       }
}];

這樣收到的通知就變成修改之后的了。

取消通知

取消通知分兩種纽什,取消未發(fā)送的通知和移除已展示過(guò)的通知措嵌。

// 移除已展示過(guò)的通知
[[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
    
// 取消還未發(fā)送的通知
[[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];

添加Action

要發(fā)送一個(gè)帶有action的通知,先注冊(cè)category芦缰。

    // 輸入動(dòng)作
    UNTextInputNotificationAction *inputAction = [UNTextInputNotificationAction actionWithIdentifier:@"inputIndentifier" title:@"輸入" options:UNNotificationActionOptionForeground textInputButtonTitle:@"回復(fù)" textInputPlaceholder:@"請(qǐng)回復(fù)"];
    
    // 接受動(dòng)作
    UNNotificationAction *commitAction = [UNNotificationAction actionWithIdentifier:@"commitIndentifier" title:@"確定" options:UNNotificationActionOptionForeground];
    
    // 取消動(dòng)作
    UNNotificationAction *cancelAction = [UNNotificationAction actionWithIdentifier:@"cancelIndentifier" title:@"取消" options:UNNotificationActionOptionDestructive];
    
    // 自定義類型
    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"categoryIndentifier" actions:@[inputAction,commitAction,cancelAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
    NSSet *set = [[NSSet alloc] initWithObjects:category, nil];
    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:set];

這里可以在程序啟動(dòng)的時(shí)候注冊(cè)企巢,后面發(fā)通知直接根據(jù)不同的標(biāo)識(shí)符選擇不同的category即可。

content.categoryIdentifier = @"categoryIndentifier";

這時(shí)候發(fā)的通知如下圖让蕾,多了三個(gè)按鈕浪规,點(diǎn)第一個(gè)輸入按鈕還能直接輸入內(nèi)容發(fā)送:


處理通知

UNUserNotificationCenterDelegate提供的兩個(gè)代理方法,第一個(gè)方法主要用來(lái)決定是否在應(yīng)用內(nèi)展示通知探孝。

// 如果在應(yīng)用內(nèi)展示通知 (如果不想在應(yīng)用內(nèi)展示笋婿,可以不實(shí)現(xiàn)這個(gè)方法)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    
    // 展示
    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);
    
//    // 不展示
//    completionHandler(UNNotificationPresentationOptionNone);
}

第二個(gè)方法用來(lái)處理用戶與推送的通知進(jìn)行的交互。

// 對(duì)通知進(jìn)行響應(yīng)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
    
    // 根據(jù)類別標(biāo)識(shí)符處理目標(biāo)反應(yīng)
    if ([response.notification.request.content.categoryIdentifier isEqualToString:@"categoryIndentifier"]) {
        [self handleResponse:response];
    }
    completionHandler();
}

- (void)handleResponse:(UNNotificationResponse *)response {
    
    NSString *actionIndentifier = response.actionIdentifier;
    
    // 處理留言
    if ([actionIndentifier isEqualToString:@"inputIndentifier"]) {
        
        UNTextInputNotificationResponse *input = (UNTextInputNotificationResponse *)response;
        NSLog(@"%@",input.userText);
        UINavigationController *navVC = (UINavigationController *)self.window.rootViewController;
        navVC.visibleViewController.view.backgroundColor = [UIColor redColor];
        
    }
    // 處理確定點(diǎn)擊事件
    else if ([actionIndentifier isEqualToString:@"commitIndentifier"]) {
        
        NSLog(@"用戶點(diǎn)確定了~~");
        UINavigationController *navVC = (UINavigationController *)self.window.rootViewController;
        navVC.visibleViewController.view.backgroundColor = [UIColor greenColor];
    }
    // 處理取消點(diǎn)擊事件
    else {
        
        NSLog(@"用戶點(diǎn)取消了~~");
        UINavigationController *navVC = (UINavigationController *)self.window.rootViewController;
        navVC.visibleViewController.view.backgroundColor = [UIColor yellowColor];
    }
}

當(dāng)然顿颅,要實(shí)現(xiàn)代理方法缸濒,前提得設(shè)置代理。這里我直接把KFADelegate設(shè)置為消息中心的代理粱腻。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self setNotificationCategorys];
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    
    return YES;
}

因?yàn)樯婕暗酱蜷_(kāi)應(yīng)用的行為庇配,所以實(shí)現(xiàn)了這個(gè)方法的 delegate 必須在 applicationDidFinishLaunching:
返回前就完成設(shè)置

自定義樣式

新建一個(gè)Notification Content Extention,配置info.plist文件


然后在- (void)didReceiveNotification:(UNNotification *)notification里取出通知的內(nèi)容并賦給UI控件展示绍些。

- (void)didReceiveNotification:(UNNotification *)notification {
    
    // 標(biāo)題
    self.titleLbl.text = notification.request.content.title;
    // 次標(biāo)題
    self.subLbl.text = notification.request.content.subtitle;
    // 內(nèi)容
    self.label.text = notification.request.content.body;
    
    UNNotificationAttachment *attachment = notification.request.content.attachments.firstObject;
    if (attachment.URL.startAccessingSecurityScopedResource) {
        // 圖片
        UIImage *temptImage = [[UIImage alloc] initWithContentsOfFile:attachment.URL.path];
        // 壓縮避免圖片過(guò)大展示不全
        NSData *imageData = UIImageJPEGRepresentation(temptImage, 1.0);
        UIImage *resultImage = [[UIImage alloc] initWithData:imageData];
        self.img.image = resultImage;
        [attachment.URL stopAccessingSecurityScopedResource];
    }
}

效果:


待解決:
1捞慌、圖片未加載全。(此問(wèn)題經(jīng)小巖同學(xué)的提醒柬批,已解決卿闹,效果見(jiàn)上圖)
2揭糕、布局不夠漂亮。

TODO

到這里基于iOS10的本地推送基本上就實(shí)現(xiàn)了锻霎,還有些東西還沒(méi)嘗試著角,比如推送音頻和視頻······

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市旋恼,隨后出現(xiàn)的幾起案子吏口,更是在濱河造成了極大的恐慌,老刑警劉巖冰更,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件产徊,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蜀细,警方通過(guò)查閱死者的電腦和手機(jī)舟铜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)奠衔,“玉大人谆刨,你說(shuō)我怎么就攤上這事」榻铮” “怎么了痊夭?”我有些...
    開(kāi)封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)脏里。 經(jīng)常有香客問(wèn)我她我,道長(zhǎng),這世上最難降的妖魔是什么迫横? 我笑而不...
    開(kāi)封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任番舆,我火速辦了婚禮,結(jié)果婚禮上矾踱,老公的妹妹穿的比我還像新娘合蔽。我一直安慰自己,他們只是感情好介返,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著沃斤,像睡著了一般圣蝎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上衡瓶,一...
    開(kāi)封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天徘公,我揣著相機(jī)與錄音,去河邊找鬼哮针。 笑死关面,一個(gè)胖子當(dāng)著我的面吹牛坦袍,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播等太,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼捂齐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了缩抡?” 一聲冷哼從身側(cè)響起奠宜,我...
    開(kāi)封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎瞻想,沒(méi)想到半個(gè)月后压真,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蘑险,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年滴肿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片佃迄。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡泼差,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出和屎,到底是詐尸還是另有隱情拴驮,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布柴信,位于F島的核電站套啤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏随常。R本人自食惡果不足惜潜沦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望绪氛。 院中可真熱鬧唆鸡,春花似錦、人聲如沸枣察。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)序目。三九已至臂痕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間猿涨,已是汗流浹背握童。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留叛赚,地道東北人澡绩。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓稽揭,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親肥卡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子溪掀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

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