百度云推送實(shí)現(xiàn)全過程

2017年1月12日
一.百度云推送
目前免費(fèi)(cocoapod不支持)
1.效果圖:
如果程序在后臺(tái)(主頁面tab在第一個(gè))于样,收到通知后的效果 【操作流程:點(diǎn)擊鮮花通知-點(diǎn)擊返回】


Paste_Image.png

如果程序默認(rèn)是開啟狀態(tài)迁霎,效果圖如下:【操作流程:點(diǎn)擊立即前往-點(diǎn)擊返回】

Paste_Image.png

2.如何加載第三方庫,參考官網(wǎng)文檔
基本原理圖:
Paste_Image.png

其實(shí)蘋果用的是deviceToken百宇,我們在如下接口獲取到deviceToken后 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

注冊到百度云庫里面考廉,百度云會(huì)返回一個(gè)對應(yīng)token的userid(之后就是以這個(gè)做設(shè)備識(shí)別)。也就是百度云對應(yīng)的 getChannelId携御,appd客戶端獲取后昌粤,發(fā)送到appServer既可(該值我們是和賬號綁定的,所以后臺(tái)要設(shè)置綁定關(guān)系)啄刹,這樣appServer就可以通過這個(gè)id來推送消息了(群發(fā)的不需要id)涮坐。
2.創(chuàng)建好應(yīng)用后,關(guān)鍵是如下制作證書上傳
具體參照如下:蘋果push證書制作全過程(含測試過程)
二.實(shí)現(xiàn)(工程和代碼相關(guān)設(shè)置)
1.工程設(shè)置

Paste_Image.png

Paste_Image.png

百度云SDK


Paste_Image.png

2.代碼設(shè)置
頭文件設(shè)置

//  AppDelegate.m
#import "BPush.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

static BOOL isBackGroundActivateApplication;

第一步:程序啟動(dòng)接口 綁定api key(百度 無賬號登錄體系)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//初始化百度推送組件
    [self startBaiDuPush:launchOptions];
    return YES;
}

- (void)startBaiDuPush:(NSDictionary *)launchOptions
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                                  if (granted) {
                                      [[UIApplication sharedApplication] registerForRemoteNotifications];
                                  }
                              }];
#endif
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

    //#warning 測試 開發(fā)環(huán)境 時(shí)需要修改BPushMode為BPushModeDevelopment 需要修改Apikey為自己的Apikey
    BPushMode pMode =  BPushModeDevelopment;
#ifdef HuBPushModeProduction_ON
    pMode = BPushModeProduction;
#endif
    NSString *key = Baidu_PUSH_API_KEY;
    [BPush registerChannel:launchOptions apiKey:key pushMode:pMode withFirstAction:@"打開" withSecondAction:@"回復(fù)" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];

    // 禁用地理位置推送 需要再綁定接口前調(diào)用。
    [BPush disableLbs];

    // App 是用戶點(diǎn)擊推送消息啟動(dòng)
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }
    //角標(biāo)清0  角標(biāo)結(jié)合我們自己的邏輯不能清空
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

// 在 iOS8 系統(tǒng)中,還需要添加這個(gè)方法驶兜。通過新的 API 注冊推送服務(wù)
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}

第二步:將蘋果返回的deviceToken装哆,注冊如百度庫,接著綁定吝秕,之后都用channel_id 替代deviceToken

//獲取手機(jī)唯一標(biāo)示  消息中心push 主推想
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [BPush registerDeviceToken:deviceToken];
    //綁定
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        if (error) return ;
        if (result) {
            // 確認(rèn)綁定成功
            if ([result[@"error_code"]intValue]!=0) {
                return;
            }
            // 獲取channel_id
            NSString *BaiDu_Channel_id = [BPush getChannelId];

            [[NSUserDefaults standardUserDefaults]setObject:BaiDu_Channel_id forKey:@"BaiDu_Channel_id"];
        }
    }];
}

// 當(dāng) DeviceToken 獲取失敗時(shí),系統(tǒng)會(huì)回調(diào)此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 獲取失敗,原因:%@",error);
}

第三步:處理通知接口

// ios7后的新接口救巷, 此方法是 用戶點(diǎn)擊了通知,應(yīng)用在前臺(tái) 或者開啟后臺(tái)并且應(yīng)用在后臺(tái) 時(shí)調(diào)起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
    _ps_Type=[userInfo[@"psType"] intValue];//自定義type消息(和后臺(tái)約定)
    NSString *message = userInfo[@"aps"][@"alert"];

    completionHandler(UIBackgroundFetchResultNewData);

    // 應(yīng)用在前臺(tái)句柠,不跳轉(zhuǎn)頁面浦译,讓用戶選擇。
    if (application.applicationState == UIApplicationStateActive) {
        [self showAlertView:message];
    }
//    殺死狀態(tài)下溯职,直接跳轉(zhuǎn)到需要添置跳轉(zhuǎn)頁面精盅。
    if (application.applicationState == UIApplicationStateInactive && !isBackGroundActivateApplication)
    {
        [self dealPushMessage:_ps_Type];
    }
    // 應(yīng)用在后臺(tái)。當(dāng)后臺(tái)設(shè)置aps字段里的 content-available 值為 1 并開啟遠(yuǎn)程通知激活應(yīng)用的選項(xiàng)
    if (application.applicationState == UIApplicationStateBackground) {
        // 此處可以選擇激活應(yīng)用提前下載郵件圖片等內(nèi)容谜酒。
        isBackGroundActivateApplication = YES;
        [self showAlertView:message];
    }
}

3.1添加個(gè)人處理相關(guān)個(gè)性化頁面

- (void)showAlertView:(NSString *)message
{
    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"消息提醒" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即前往", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self dealPushMessage:_ps_Type];
    }
}

//程序主界面首頁底部menutar類型
typedef NS_ENUM(NSInteger, HuMainPageMenuBarType) {
    HuMainPageMenuBarTypeWardPatient  = 1,//病區(qū)患者
    HuMainPageMenuBarTypeEducationClass  = 2,//宣教課程
    HuMainPageMenuBarTypePersonalCenter  = 3,//個(gè)人中心
};
- (void)dealPushMessage:(HuMessagePushType)pushType
{
    if (![HuConfigration loginStatus]) {
        loginViewController * loginVC = [[loginViewController alloc] init];
        [[[UIApplication sharedApplication] delegate] window].rootViewController = loginVC;
    }
    else
    {
        switch (pushType) {
            case HuMessagePushTypeMain:
            {
                [self goToMainPage:HuMainPageMenuBarTypeWardPatient];
            }
                break;
           case HuMessagePushTypeDonateFlowerMessage:
            {
                [self gotoViewControllerStr:@"FlowerMessViewController" WithMenuBar:HuMainPageMenuBarTypePersonalCenter];
            }
                break;
            case HuMessagePushTypeSystemMessage:
            {
                [kNotificationCenter postNotificationName:kNotificationRed object:nil];
                [self gotoViewControllerStr:@"SystemMessagesViewController" WithMenuBar:HuMainPageMenuBarTypePersonalCenter];
            }
                break;

            default:
                break;
        }

    }
}

- (void)gotoViewControllerStr:(NSString*)vcStr WithMenuBar:(HuMainPageMenuBarType)type
{
    [self goToMainPage:type];
    NSInteger i = type - 1;
      //選擇對應(yīng)的控制器數(shù)組叹俏,在將其push進(jìn)入
    UINavigationController *nav = [[_customVc childViewControllers] objectAtIndex:i];
    UIViewController *vc = [[NSClassFromString(vcStr) alloc] init];
    [nav pushViewController:vc animated:YES];
    [_customVc hiddenTabBar];

}

- (void)goToMainPage:(HuMainPageMenuBarType)type
{
    if (!_customVc)
    {
        CustomMyViewController *custom = [[CustomMyViewController alloc]init];
        custom.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        _window.rootViewController = custom;
        _customVc = custom;
    }
    if(type >= HuMainPageMenuBarTypeWardPatient  && type <= HuMainPageMenuBarTypePersonalCenter){
          //將主頁底部點(diǎn)擊下班設(shè)置正確
        [_customVc tabMenuBarWithType:type];
    }
}

第四步.如果獲取的channel_id,需要跟對應(yīng)的賬號綁定甚带,我們就需要程序賬號登錄后她肯,告訴后臺(tái)appServer綁定關(guān)系。之后推送相關(guān)都從后臺(tái)appServer發(fā)起鹰贵。
程序程序之后主界面 綁定下就可以

- (void)viewDidLoad
{
   [self bindChannelIdWithAccount];
}

- (void)bindChannelIdWithAccount
{
    NSString *BaiDu_Channel_id = [[NSUserDefaults standardUserDefaults]objectForKey:@"BaiDu_Channel_id"];
    NSDictionary *param = @{@"deviceChannelId":BaiDu_Channel_id};

    NSString *url=[NSString stringWithFormat:@"%@/api/testModle/bindDevice",quanQaunURL];
    [QQRequest post:url param:param view:nil success:^(NSDictionary *dic) {
    } error:nil failure:nil];
}

三.其他
1.請求Push 常見錯(cuò)誤碼
BPushErrorCode_Success = 0,
BPushErrorCode_MethodTooOften = 22, // 調(diào)用過于頻繁
BPushErrorCode_NetworkInvalible = 10002, // 網(wǎng)絡(luò)連接問題
BPushErrorCode_InternalError = 30600, // 服務(wù)器內(nèi)部錯(cuò)誤
BPushErrorCode_MethodNodAllowed = 30601, // 請求方法不允許
BPushErrorCode_ParamsNotValid = 30602, // 請求參數(shù)錯(cuò)誤
BPushErrorCode_AuthenFailed = 30603, // 權(quán)限驗(yàn)證失敗
BPushErrorCode_DataNotFound = 30605, // 請求數(shù)據(jù)不存在
BPushErrorCode_RequestExpired = 30606, // 請求時(shí)間戳驗(yàn)證超時(shí)
BPushErrorCode_BindNotExists = 30608, // 綁定關(guān)系不存在
2.目前暫時(shí)沒用到(以后可能會(huì)設(shè)計(jì)晴氨,給特點(diǎn)標(biāo)簽的設(shè)備推送消息)
標(biāo)簽組播:推送給打上某一個(gè)標(biāo)簽的一組設(shè)備。為iOS設(shè)備打標(biāo)簽需要通過調(diào)用iOS客戶端SDK中的setTags方法來設(shè)置所屬的Tag 每個(gè)應(yīng)用最多可以定義10000個(gè)標(biāo)簽碉输;每個(gè)標(biāo)簽對應(yīng)的設(shè)備數(shù)沒有限制

3.后臺(tái)推送參數(shù)添加content-available: 1 (靜默推送)【暫時(shí)也沒用】

4.ios9新特性 【 暫時(shí)也沒用】


Paste_Image.png

5.ios10富文本消息 【暫時(shí)也沒用】


Paste_Image.png

2016年11月16日
一.百度云推送測試流程總結(jié)
第一步:登錄如下賬號(百度云網(wǎng)站部署狀態(tài)改變籽前,不會(huì)影響生產(chǎn)的<生產(chǎn)上客服推送是另一套機(jī)制推送>,代碼推送狀態(tài)修改就會(huì)有影響了)
http://push.baidu.com/

Paste_Image.png

二.代碼斷點(diǎn)調(diào)試 獲取百度返回的 BaiDu_Channel_id

Paste_Image.png

三.一般指定設(shè)備id 推送消息


Paste_Image.png

正常現(xiàn)象:

Paste_Image.png

ps:
注意測試的時(shí)候appid一定要選對


Paste_Image.png
Paste_Image.png

如果您發(fā)現(xiàn)本文對你有所幫助枝哄,如果您認(rèn)為其他人也可能受益肄梨,請把它分享出去。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末挠锥,一起剝皮案震驚了整個(gè)濱河市众羡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蓖租,老刑警劉巖粱侣,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異蓖宦,居然都是意外死亡齐婴,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門稠茂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來柠偶,“玉大人,你說我怎么就攤上這事睬关∮盏#” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵共螺,是天一觀的道長该肴。 經(jīng)常有香客問我情竹,道長藐不,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任秦效,我火速辦了婚禮雏蛮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘阱州。我一直安慰自己挑秉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布苔货。 她就那樣靜靜地躺著犀概,像睡著了一般。 火紅的嫁衣襯著肌膚如雪夜惭。 梳的紋絲不亂的頭發(fā)上姻灶,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天,我揣著相機(jī)與錄音诈茧,去河邊找鬼产喉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的曾沈。 我是一名探鬼主播这嚣,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼塞俱!你這毒婦竟也來了姐帚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤障涯,失蹤者是張志新(化名)和其女友劉穎卧土,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體像樊,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡尤莺,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了生棍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片颤霎。...
    茶點(diǎn)故事閱讀 39,779評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖涂滴,靈堂內(nèi)的尸體忽然破棺而出友酱,到底是詐尸還是另有隱情,我是刑警寧澤柔纵,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布缔杉,位于F島的核電站,受9級特大地震影響搁料,放射性物質(zhì)發(fā)生泄漏或详。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一郭计、第九天 我趴在偏房一處隱蔽的房頂上張望霸琴。 院中可真熱鬧,春花似錦昭伸、人聲如沸梧乘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽选调。三九已至,卻和暖如春灵份,著一層夾襖步出監(jiān)牢的瞬間仁堪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工各吨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留枝笨,地道東北人袁铐。 一個(gè)月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像横浑,于是被迫代替她去往敵國和親剔桨。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評論 2 354

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

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,100評論 1 32
  • 點(diǎn)擊查看原文 Web SDK 開發(fā)手冊 SDK 概述 網(wǎng)易云信 SDK 為 Web 應(yīng)用提供一個(gè)完善的 IM 系統(tǒng)...
    layjoy閱讀 13,760評論 0 15
  • 前言 在Android開發(fā)中徙融,消息推送功能的使用非常常見洒缀。 推送消息截圖 為了降低開發(fā)成本,使用第三方推送是現(xiàn)今較...
    BillyLu1994閱讀 4,416評論 0 2
  • 背景 我所在的公司是一家傳統(tǒng)互聯(lián)網(wǎng)+教育公司欺冀,推送業(yè)務(wù)是從去年開始的树绩,前后也經(jīng)歷了多次迭代,沒有大牛隐轩,也沒有架構(gòu)師...
    風(fēng)雪橋客閱讀 1,002評論 0 0
  • 推送通知饺饭,是現(xiàn)在的應(yīng)用必不可少的功能。那么在 iOS 中职车,我們是如何實(shí)現(xiàn)遠(yuǎn)程推送的呢瘫俊?iOS 的遠(yuǎn)程推送原理又是什...
    皮皮瑞閱讀 1,299評論 0 3