二秸滴、<iOS 推送> 本地推送

最近武契,再次看路遙 《平凡的世界》時,多多少少有自己的影子在里面荡含,覺得沒有什么愛與不愛的咒唆,在一起就是一種幸福吧。就像潤葉和向前在一起释液,雖然向前失去了雙腿全释,他最終得到一個好老婆和一個可愛的兒子。有時候覺得和誰在一起真的不重要误债,重要是她開心浸船,你也覺得幸福。生活應(yīng)該是柴米油鹽寝蹈,而非風(fēng)花雪月啦李命。

一、 iOS 10 本地推送的效果圖

本文將重點講述如何實現(xiàn) iOS 10的本地推送通知的用法箫老,如下是效果圖封字。

本地推送.gif

上面的 gif 圖片都已經(jīng)本地推送的如下功能:

  • 1、通知附件中有視頻
  • 2槽惫、 通知中有通知標題周叮、副標題和通知內(nèi)容
  • 3、 通知 action
  • 4界斜、前臺和后臺都能接收到通知仿耽。

二、 iOS 10 本地推送實現(xiàn)思路

關(guān)于 iOS 10 本地推送實現(xiàn)思路分為如下三個步驟:
0>各薇、手動導(dǎo)入資源文件项贺,如下圖。


Snip20170725_34.png

1>峭判、應(yīng)用啟動時开缎,注冊通知,并設(shè)置 Action 按鍵的樣式和標題林螃。

2>奕删、設(shè)置通知的內(nèi)容,附件疗认、通知的觸發(fā)條件完残。

3>伏钠、在代理中處理相對應(yīng)的內(nèi)容。一般是處理 用戶點擊那個按鍵谨设,并處理相對應(yīng)的事件熟掂。

三、 iOS 10 本地代碼的實現(xiàn)

1扎拣、在 AppDelegate.m 中
  • A赴肚、首先要導(dǎo)入頭文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
  • B、在 didFinishLaunchingWithOptions 方法中注冊通知二蓝,主要思路是實現(xiàn)如下的內(nèi)容:
    1>誉券、注冊通知 requestAuthorizationWithOptions,在此方法中侣夷,注冊通知需要有授權(quán)横朋,設(shè)置推送的聲音、Badge 等四種模式百拓。

2>琴锭、設(shè)置推送的 Action,點擊 Action 按鍵有三種狀態(tài)衙传,UNNotificationActionOptionForeground 直接開啟應(yīng)用决帖,UNNotificationActionOptionDestructive 取消,
UNNotificationActionOptionAuthenticationRequired 需要解鎖


Snip20170725_35.png

3>蓖捶、將本地推送包裝在 UNNotificationCategory 對象中地回,記得設(shè)置 UNNotificationCategory 對象的標識符。

4>俊鱼、將UNNotificationCategory 對象加入在通知中心去刻像。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {

        //ios 10 版本以上的通知
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //注冊通知
        [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge| UNAuthorizationOptionSound|UNAuthorizationOptionAlert|UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) {
            NSLog(@"錯誤的要求通知,%@",error);
            
        }];
        
        // Action 內(nèi)容 UNNotificationActionOptionForeground 點擊 actionbutton 會跳轉(zhuǎn)到應(yīng)用中
        UNNotificationAction *actionOne = [UNNotificationAction actionWithIdentifier:@"action1" title:@"action1" options:UNNotificationActionOptionForeground];
        
        UNNotificationAction *actionTwo = [UNNotificationAction actionWithIdentifier:@"action2" title:@"action2" options:UNNotificationActionOptionForeground];
        
        UNNotificationAction *actionThree = [UNNotificationAction actionWithIdentifier:@"action3" title:@"action3" options:UNNotificationActionOptionForeground];
        
        //分類
        UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"category" actions:@[actionOne,actionTwo,actionThree] intentIdentifiers:@[] options:0];
        
        //添加分類
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject:category]];
        
        
    }else if([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0){
        //iOS 10 ~ iOS 8 之間的通知
        UIMutableUserNotificationAction *action1 = [UIMutableUserNotificationAction new];
        action1.identifier =  @"actionOne";
        action1.title = @"actionOne";
        action1.activationMode = UIUserNotificationActivationModeForeground;
        
        UIMutableUserNotificationCategory * category = [[UIMutableUserNotificationCategory alloc] init] ;
        
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge  categories:[NSSet setWithObject:category]];
 [application registerUserNotificationSettings:setting];
        
    }else if([[UIDevice currentDevice].systemVersion doubleValue] < 8.0){
    
        // 低于 iOS 8 以下的系統(tǒng)
    }
    // Override point for customization after application launch.
    return YES;
}
2并闲、在 ViewController.m 文件中
  • A细睡、導(dǎo)入頭文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
  • B、設(shè)置通知代碼
- (void)viewDidLoad {
   [super viewDidLoad];
   [UNUserNotificationCenter currentNotificationCenter].delegate = self;
   // Do any additional setup after loading the view, typically from a nib.
}
  • C帝火、推送代理方法的實現(xiàn)
    1>溜徙、willPresentNotification 實現(xiàn)此代理方法可以接收來自前臺的通知。當實現(xiàn) completionHandler 時犀填,如果加入 UNNotificationPresentationOptionBadge 時蠢壹,前臺不會接收到通知。

    2>九巡、didReceiveNotificationResponse 此方法通過 Action 標識來識別用戶點擊那個 Action 按鍵图贸。這樣我們可以通過這個來處理相對應(yīng)的事件。

  #pragma mark - UNNotification
  //此方法能在前臺收到通知
   - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{

    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);
}

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    if ([response.actionIdentifier isEqualToString:@"action1"]) {
        self.noticeImage.image = [UIImage imageNamed:@"1"];
    }else if([response.actionIdentifier isEqualToString:@"action2"]){
        self.noticeImage.image = [UIImage imageNamed:@"2"];
    
    }else if([response.actionIdentifier isEqualToString:@"action3"]){
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle:@"通知標題" message:@"hello world" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    completionHandler();
}
  • D、設(shè)置推送內(nèi)容和附件


    Snip20170725_36.png

    1>求妹、設(shè)置推送內(nèi)容乏盐,UNMutableNotificationContent 對象中是用來寫推送的內(nèi)容的佳窑,推送的聲音制恍,推送的角標。一定神凑、一定净神、一定要注意,UNMutableNotificationContent 對象 categoryIdentifier 屬性要與注冊的標識一樣溉委,否則不能加載 Action 按鍵鹃唯。

    2>、設(shè)置推送附件瓣喊,UNNotificationAttachment 對象是用于處理附件的坡慌,本地推送附件可以是 音頻、視頻藻三、圖片洪橘、gif 動圖。一定一定要注意棵帽,使用本地的資源熄求,不能用網(wǎng)上的資源,否則 UNNotificationAttachment 對象為空逗概。其中資源文件的大小如下截圖弟晚。


    3>、觸發(fā)推送逾苫,本地有三種推送方式:時間卿城、日期、地區(qū)铅搓。本案例使用的是 時間 UNTimeIntervalNotificationTrigger瑟押。

    4>、將推送的內(nèi)容和觸發(fā)條件包裝在 UNNotificationRequest 對象中狸吞。

    5>勉耀、將 UNNotificationRequest 對象 加入在 UNUserNotificationCenter 對象中。

#pragma  mark - 發(fā)送通知
- (IBAction)sendNotice:(id)sender {
    //1.設(shè)置通知內(nèi)容
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"通知標題";
    content.subtitle = @"副標題";
    content.body = @"iOS 10 本地通知文本內(nèi)容蹋偏,你好吖便斥,親!M肌枢纠!";
    content.badge = [NSNumber numberWithInteger:1];
    content.categoryIdentifier = @"category";
    content.sound = [UNNotificationSound defaultSound];
    
    //2.設(shè)備通知的附件
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"flv視頻測試用例1.mp4" withExtension:@""];

    UNNotificationAttachment *attchment = [UNNotificationAttachment attachmentWithIdentifier:@"2" URL:url options:nil error:nil];
    if (attchment == nil) {
        NSLog(@"空的item");
        return;
    }
    content.attachments = @[attchment];
    
    //3.觸發(fā)本地通知
    UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:2 repeats:NO];
    
    //4.將通知的信息和觸發(fā)條件放在 request中
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"request" content:content trigger:trigger];
    //5. 添加通知
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        
    }];

}

完整代碼,多謝你完整的讀完本文黎棠,感恩晋渺!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末镰绎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子木西,更是在濱河造成了極大的恐慌畴栖,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件八千,死亡現(xiàn)場離奇詭異吗讶,居然都是意外死亡,警方通過查閱死者的電腦和手機恋捆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門照皆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人沸停,你說我怎么就攤上這事膜毁。” “怎么了愤钾?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵瘟滨,是天一觀的道長。 經(jīng)常有香客問我绰垂,道長室奏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任劲装,我火速辦了婚禮胧沫,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘占业。我一直安慰自己绒怨,他們只是感情好,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布谦疾。 她就那樣靜靜地躺著南蹂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪念恍。 梳的紋絲不亂的頭發(fā)上六剥,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天,我揣著相機與錄音峰伙,去河邊找鬼疗疟。 笑死,一個胖子當著我的面吹牛瞳氓,可吹牛的內(nèi)容都是我干的策彤。 我是一名探鬼主播,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼店诗!你這毒婦竟也來了裹刮?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤庞瘸,失蹤者是張志新(化名)和其女友劉穎捧弃,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恕洲,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡塔橡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了霜第。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡户辞,死狀恐怖泌类,靈堂內(nèi)的尸體忽然破棺而出许昨,到底是詐尸還是另有隱情革答,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布拙绊,位于F島的核電站双仍,受9級特大地震影響枢希,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜朱沃,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一苞轿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧逗物,春花似錦搬卒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至失暴,卻和暖如春坯门,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背逗扒。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工古戴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人缴阎。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓允瞧,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子述暂,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

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