iOS-推送(基礎(chǔ))

一、iOS推送原理

<p>IOS推送消息是許多IOS應(yīng)用都具備的功能,最近也在研究這個(gè)功能,參考了很多資料終于搞定了绢彤,下面就把步驟拿出來(lái)分享下:</p>
<p>iOS消息推送的工作機(jī)制可以簡(jiǎn)單的用下圖來(lái)概括:</p>

iOS消息推送機(jī)制

<p>Provider是指某個(gè)iPhone軟件運(yùn)用的Push服務(wù)器,APNS是Apple Push Notification Service的縮寫蜓耻,是蘋果的服務(wù)器茫舶。</p>
<p>上圖可以分為三個(gè)階段:</p>
<p>第一階段:應(yīng)用程序的服務(wù)器把要發(fā)送的消息、目的iPhone的標(biāo)識(shí)打包刹淌,發(fā)給APNS饶氏。</p>
<p>第二階段:APNS在自身的已注冊(cè)Push服務(wù)的iPhone列表中,查找有相應(yīng)標(biāo)識(shí)的iPhone有勾,并把消息發(fā)送到iPhone疹启。 </p>
<p>第三階段:iPhone把發(fā)來(lái)的消息傳遞給相應(yīng)的應(yīng)用程序,并且按照設(shè)定彈出Push通知蔼卡。</p>

iOS推送工作流程

<p>從上圖我們可以看到:</p>
<p>1喊崖、應(yīng)用程序注冊(cè)消息推送。</p>
<p>2雇逞、iOS從APNS Server獲取device token荤懂,應(yīng)用程序接收device token。</p>
<p>3塘砸、應(yīng)用程序?qū)evice token發(fā)送給PUSH服務(wù)端程序节仿。</p>
<p>4、服務(wù)端程序向APNS服務(wù)發(fā)送消息掉蔬。</p>
<p> 5廊宪、APNS服務(wù)將消息發(fā)送給iPhone應(yīng)用程序。</p>
<p>無(wú)論是iPhone客戶端和APNS女轿,還是Provider和APNS箭启,都需要通過(guò)證書進(jìn)行連接。</p>

二蛉迹、創(chuàng)建推送證書

1岩调、生成CSR文件

<p>到鑰匙串的證書頒發(fā)機(jī)構(gòu)請(qǐng)求證書</p>

從證書頒發(fā)機(jī)構(gòu)請(qǐng)求證書

<p>填寫你的郵箱和常用名稱茬末,并選擇保存到硬盤</p>

cd5e9289-f943-3e8a-804f-35f452238d95.jpg
2睡陪、創(chuàng)建推送證書

<p>到要?jiǎng)?chuàng)建推送的App ID </p>

要?jiǎng)?chuàng)建推送證書的App ID詳情頁(yè)面

<p>點(diǎn)擊右側(cè)的 Create Certificate...,</p>
<p>點(diǎn)擊Continue</p>

點(diǎn)擊繼續(xù)

<p> 選擇CSR文件巴席,選擇剛才創(chuàng)建的CSR文件即可大猛,點(diǎn)擊繼續(xù)</p>

選擇CSR文件

<p>創(chuàng)建證書完成扭倾,點(diǎn)擊下載可得到要用到的cer證書</p>

下載推送證書(cer文件)

<p>創(chuàng)建推送證書完成,App ID詳情頁(yè)面</p>

創(chuàng)建推送證書完成挽绩,App ID詳情頁(yè)面

<p>雙擊已經(jīng)下載的推送證書膛壹,到鑰匙串中找到證書,可以導(dǎo)出成為.p12文件</p>

鑰匙串中找到證書

<p>此時(shí),推送證書環(huán)境已經(jīng)完成模聋,接下來(lái)代碼開發(fā)即可</p>

三肩民、推送程序開發(fā)

//
//  AppDelegate.m
//  推送
//
//  Created by 泛在呂俊衡 on 2017/6/23.
//  Copyright ? 2017年 anjohnlv. All rights reserved.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>


@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([[UIDevice currentDevice].systemVersion floatValue]>=10.0) {
//        iOS10以上的
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate=self;
        [center requestAuthorizationWithOptions: UNAuthorizationOptionBadge |UNAuthorizationOptionSound |
         UNAuthorizationOptionAlert |UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) {
             if (error == nil) {
                 NSLog(@"注冊(cè)成功");
                 [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                     NSLog(@"%@", settings);
                 }];
             }
             else {
                 NSLog(@"注冊(cè)失敗");
             }
        }];
    } else if([[UIDevice currentDevice].systemVersion floatValue]>=8.0){
            //ios8的
        [application registerUserNotificationSettings: [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
    } else {
//        iOS8以下
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    }
    
    //注冊(cè)token
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    return YES;
}

//獲取到token,token需要提交到服務(wù)器
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"token:%@", deviceToken);
    
}
//獲取到token失敗
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"tokenError:%@", error.description);
}

//ios6-10接收到信息
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler {
    NSLog(@"%@", userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}
// iOS 10收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的請(qǐng)求
    UNNotificationContent *content = request.content; // 收到推送的消息內(nèi)容
    NSNumber *badge = content.badge;  // 推送消息的角標(biāo)
    NSString *body = content.body;    // 推送消息體
    UNNotificationSound *sound = content.sound;  // 推送消息的聲音
    NSString *subtitle = content.subtitle;  // 推送消息的副標(biāo)題
    NSString *title = content.title;  // 推送消息的標(biāo)題
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 前臺(tái)收到遠(yuǎn)程通知:%@", userInfo);
        
    }
    else {
        // 判斷為本地通知
        NSLog(@"iOS10 前臺(tái)收到本地通知:{\\\\nbody:%@链方,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@持痰,\\\\nsound:%@,\\\\nuserInfo:%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要執(zhí)行這個(gè)方法祟蚀,選擇是否提醒用戶工窍,有Badge、Sound前酿、Alert三種類型可以設(shè)置
}

// 通知的點(diǎn)擊事件
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的請(qǐng)求
    UNNotificationContent *content = request.content; // 收到推送的消息內(nèi)容
    NSNumber *badge = content.badge;  // 推送消息的角標(biāo)
    NSString *body = content.body;    // 推送消息體
    UNNotificationSound *sound = content.sound;  // 推送消息的聲音
    NSString *subtitle = content.subtitle;  // 推送消息的副標(biāo)題
    NSString *title = content.title;  // 推送消息的標(biāo)題
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"iOS10 收到遠(yuǎn)程通知:%@", userInfo);
        
    }
    else {
        // 判斷為本地通知
        NSLog(@"iOS10 收到本地通知:{\\\\nbody:%@患雏,\\\\ntitle:%@,\\\\nsubtitle:%@,\\\\nbadge:%@,\\\\nsound:%@罢维,\\\\nuserInfo:%@\\\\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    // Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.
    completionHandler();  // 系統(tǒng)要求執(zhí)行這個(gè)方法
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末淹仑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子肺孵,更是在濱河造成了極大的恐慌匀借,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件平窘,死亡現(xiàn)場(chǎng)離奇詭異怀吻,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)初婆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門蓬坡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人磅叛,你說(shuō)我怎么就攤上這事屑咳。” “怎么了弊琴?”我有些...
    開封第一講書人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵兆龙,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我敲董,道長(zhǎng)紫皇,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任腋寨,我火速辦了婚禮聪铺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘萄窜。我一直安慰自己铃剔,他們只是感情好撒桨,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著键兜,像睡著了一般凤类。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上普气,一...
    開封第一講書人閱讀 49,007評(píng)論 1 284
  • 那天谜疤,我揣著相機(jī)與錄音,去河邊找鬼现诀。 笑死茎截,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的赶盔。 我是一名探鬼主播企锌,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼于未!你這毒婦竟也來(lái)了撕攒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤烘浦,失蹤者是張志新(化名)和其女友劉穎抖坪,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闷叉,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡擦俐,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了握侧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蚯瞧。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖品擎,靈堂內(nèi)的尸體忽然破棺而出埋合,到底是詐尸還是另有隱情,我是刑警寧澤萄传,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布甚颂,位于F島的核電站,受9級(jí)特大地震影響秀菱,放射性物質(zhì)發(fā)生泄漏振诬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一衍菱、第九天 我趴在偏房一處隱蔽的房頂上張望赶么。 院中可真熱鬧,春花似錦梦碗、人聲如沸禽绪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)印屁。三九已至,卻和暖如春斩例,著一層夾襖步出監(jiān)牢的瞬間雄人,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工念赶, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留础钠,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓叉谜,卻偏偏與公主長(zhǎng)得像旗吁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子停局,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

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