1. 程式人生 > >百度推送--iOS(一)

百度推送--iOS(一)

1、  百度推送封裝了蘋果的APNS和google的SMS推送,作為開發者可以通過百度來完成這兩個平臺的推送。

百度推送開發指南:http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/guideios

  蘋果APNS開發相關指南請參考蘋果開發者網站:https://developer.apple.com/

本文是完成簡單的功能,可以傳送通知到客戶端,之後我會將這部分內容寫成一個phonegap外掛,以後在做推送時直接呼叫就可以了。

2、相關準備工作

在此之前,需要進入百度雲推送管理控制檯→開發者服務→雲推送→推送設定,  新建一個工程,百度回返回給所建工程的的一些資訊:

3、新建一個工程,匯入第三方的包和標頭檔案;

4、新建一個Property List 檔案將百度返回給我們的工程資訊添進去;


5、將匯入的檔案修改為非ARC模式:


6、開啟AppDelegate.m引用標頭檔案同時申請要用到的變數:

#import "MainViewController.h"
#import "BPush.h"
#import "JSONKit.h"
#import <Cordova/CDVPlugin.h>
@interface AppDelegate ()

@property (nonatomic, retain) NSString *appId;
@property (nonatomic, retain) NSString *channelId;
@property (nonatomic, retain) NSString *userId;


@end

@implementation AppDelegate

@synthesize window, viewController;

@synthesize appId, channelId, userId;


7、註冊push
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    //初始化push
    [BPush setupChannel:launchOptions];
    [BPush setDelegate:self];
    //在程式圖示的右上角顯示數字
    [application setApplicationIconBadgeNumber:0];
    //管理遠端通知  方法來與蘋果推送通知服務註冊
    [application registerForRemoteNotificationTypes:
     /*推送的型別*/
     UIRemoteNotificationTypeAlert
     | UIRemoteNotificationTypeBadge
     | UIRemoteNotificationTypeSound];

    NSLog(@"++++++++++++++++++++++");
    
    return YES;

}

8、因為在推送時開發者需要知道客戶端手機的userid 和 channelid,所以我們需要在程式中獲取到這些資訊:
- (void) onMethod:(NSString*)method response:(NSDictionary*)data {
    NSLog(@"On method:%@", method);
    NSLog(@"data:%@", [data description]);
    NSDictionary* res = [[NSDictionary alloc] initWithDictionary:data];
    
    if ([BPushRequestMethod_Bind isEqualToString:method]) {
        //從字典裡取值
        NSString *appid = [res valueForKey:BPushRequestAppIdKey];
        NSString *userid = [res valueForKey:BPushRequestUserIdKey];
        NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
        NSString *requestid = [res valueForKey:BPushRequestRequestIdKey];
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        
        if (returnCode == BPushErrorCode_Success) {
         
            
            // 在記憶體中備份,以便短時間內進入可以看到這些值,而不需要重新bind
            self.appId = appid;
            self.channelId = channelid;
            self.userId = userid;
            
            [[NSUserDefaults standardUserDefaults] setObject:userId
                                                      forKey:@"BAIDUNOTIFICATION_USERID"];
            [[NSUserDefaults standardUserDefaults] setObject:channelId
                                                      forKey:@"BAIDUNOTIFICATION_CHANNELID"];
            
        }
    } else if ([BPushRequestMethod_Unbind isEqualToString:method]) {
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        if (returnCode == BPushErrorCode_Success) {
            
        }
    }
    
    NSLog(@"%@===========%@==============",method,[data description]);
    
}
9、在客戶端接收推送來的資訊:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    NSString *alert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    //程式執行的狀態判斷
    if (application.applicationState == UIApplicationStateActive) {
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification"
                                                            message:[NSString stringWithFormat:@"The application received this remote notification while it was running:\n%@", alert]
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    // 寫程式圖示左上角顯示數字
    [application setApplicationIconBadgeNumber:0];
    //推送反饋
    [BPush handleNotification:userInfo];
        NSLog(@"%@",[userInfo JSONString]);
        NSLog(@"didReceiveRemoteNotification=======%@\n=========%@\n========%@\n",self.appId,self.userId,self.channelId);
}
11、推送之後,由客戶端返回推送是成功還是失敗:
- (void)application:(UIApplication *)application
   didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
   
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token];
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannel];
    NSLog(@"%@", deviceToken);
}
//失敗
- (void)                                 application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
       // re-post ( broadcast )
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotificationError object:error];
    
    NSLog(@"Error in registration. Error: %@", error);
    
}
12、現在基本的程式碼工作已經完成,在我們執行程之前需要把我們的推送證書由p12格式轉換成pem格式,證書轉換具體方法請參考蘋果官網:


13、Ok,在真機上執行我們的工程,這是獲取到得手機的資料:



14、開啟百度開發者服務→雲推送→通知 ,選擇新增通知推送,這樣在客戶端有網的情況下就可以將通知傳送到客戶端上。

15、demo下載請戳:https://github.com/dengfeng520/GSbaidupush