Kony integrates Baidu Push-IOS

Note: Please refer to Baidu Push IOS User Manual, console management, please refer to Baidu Push IOS Integration Guide

     All rights reserved, please indicate the source when reprinting, thank you!

  1. Open the SDK package provided by Baidu, find the LibBPush folder, and open it. Delete JSONKit.h and JSONKit.m in the opensource folder (because the IOS project compiled by kony already contains this class)

2.   Delete the JSONKit class file, correspondingly delete the statement ( #import " JSONKit.h " ) that references this class in other files ( BpushClass.m )

3. Modify the code in several places: 

in OpenUDID.m

Comment the code below

//static NSString * const kOpenUDIDDescription = @"OpenUDID_with_iOS6_Support"; 
    修改以下代码
CC_MD5( cStr, strlen(cStr), result ); 
修改为   CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%08x"
修改为   @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%08lx"
(NSUInteger)(arc4random() % NSUIntegerMax)];
    修改为   (unsigned long)(arc4random() % NSUIntegerMax)];

4. Create and configure the BPushConfig.plist file (you can directly export the plist file provided by Baidu under Demo, and copy it under the project) 

Create a new Property List file in the project, name it BPushConfig.plist, and add the following keys:

“API_KEY” = “pDUCHGTbD346jt2klpHRjHp7”
“DEBUG” = NO
“BPUSH_CHANNEL” = “91”

API_KEY : Required. The api key automatically assigned by the Baidu Developer Center for each app can be viewed in the basic information of the app in the Developer Center.

PRODUCTION_MODE : Required. App release mode. When developing certificate signing, the value is set to "NO"; when publishing certificate signing, the value is set to "YES" . Please modify and set this value correctly when debugging and publishing the application, so that the push notification cannot be reached.

DEBUG : optional. Push SDK debug mode switch, when the value is YES, will open the SDK log.

BPUSH_CHANNEL : Optional. Channel number, Cloud Push will conduct statistics, and you can see the statistics on the console.

5. Integrate the most critical code below:

Create a new class under Xcode, take the iosbdpush class as an example.

Add the following code to iosbdpush.h:

Note: The iosbdpush class inherits from NSObject @interfa iosbdpush : NSObject

@property (strong, nonatomic) NSString *appId;
@property (strong, nonatomic) NSString *channelId;
@property (strong, nonatomic) NSString *userId;
 
+(id)shareInstance;
-(void)initBPush;
-(NSString *) getUserId_kony;
-(NSString *) getChannelId_kony;
-(void)setDeviceToken:(NSString *)deviceToken;
-(void)setPushAPIKey:(NSString *)apikey;

Add the following code in iosbdpush.m:

#import "BPush.h"
#import "OpenUDID.h"
 
@implementation iosbdpush
@synthesize appId, channelId, userId;
 
+(id)shareInstance
{
    return [[iosbdpush alloc] init];
}
 
-(void)initBPush
{
    NSLog(@"=======initBPush======");
    [BPush setupChannel:nil]; // 必须
    iosbdpush *obj = [[iosbdpush alloc] init];
    [BPush setDelegate:obj]; // 必须。参数对象必须实现onMethod: response:方法,本示例中为self
 
    //[BPush bindChannel];    
    // [BPush setAccessToken:@"3.ad0c16fa2c6aa378f450f54adb08039.2592000.1367133742.282335-602025"];  // 可选。api key绑定时不需要,也可在其它时机调用
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSLog(@"=========== phoneVersion:%@",phoneVersion);
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIApplication *application = [UIApplication sharedApplication];
        [application registerForRemoteNotifications];
    }else
    {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
}
 
-(NSString *) getUserId_kony
{
    return [BPush getUserId];
}
-(NSString *) getChannelId_kony
{
    return [BPush getChannelId];
}
 
-(void)setDeviceToken:(NSString *)deviceToken
{
    NSString *hexToken = [NSString stringWithFormat:@"<%@>",deviceToken];
    
    NSData* deviceTokenData = [self dataFromHexString:hexToken];
    NSLog(@"deviceTokenData NSData:%@",deviceTokenData);
    [BPush registerDeviceToken:deviceTokenData]; // 必须
    
    [BPush bindChannel]; // 必须。可以在其它时机调用,只有在该方法返回(通过onMethod:response:回调)绑定成功时,app才能接收到Push消息。一个app绑定成功至少一次即可(如果access token变更请重新绑定)。
}
 
// 必须,如果正确调用了setDelegate,在bindChannel之后,结果在这个回调中返回。
// 若绑定失败,请进行重新绑定,确保至少绑定成功一次
- (void) onMethod:(NSString*)method response:(NSDictionary*)data
{
    NSLog(@"On method:%@", method);
    NSLog(@"data:%@", [data description]);
    NSDictionary* res = [[[NSDictionary alloc] initWithDictionary:data] autorelease];
    if ([BPushRequestMethod_Bind isEqualToString:method])
    {
        NSString *appid = [res valueForKey:BPushRequestAppIdKey];
        NSString *userid = [res valueForKey:BPushRequestUserIdKey];
        NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
        
        NSLog(@"appid--userid--channelid==%@  %@  %@",appid, userid, channelid);
    }
}
//转换device token
-(NSData *) dataFromHexString:(NSString *) hexstr
{
    NSMutableData *data = [[NSMutableData alloc] init];
    NSString *inputStr = [hexstr uppercaseString];
    
    NSString *hexChars = @"0123456789ABCDEF";
    
    Byte b1,b2;
    b1 = 255;
    b2 = 255;
    for (int i=0; i<hexstr.length; i++) {
        NSString *subStr = [inputStr substringWithRange:NSMakeRange(i, 1)];
        NSRange loc = [hexChars rangeOfString:subStr];
        
        if (loc.location == NSNotFound) continue;
        
        if (255 == b1) {
            b1 = (Byte)loc.location;
        }else {
            b2 = (Byte)loc.location;
            
            //Appending the Byte to NSData
            Byte *bytes = malloc(sizeof(Byte) *1);
            bytes[0] = ((b1<<4) & 0xf0) | (b2 & 0x0f);
            [data appendBytes:bytes length:1];
            
            b1 = b2 = 255;
        }
    }
    
    return data;
}

6. Integrate push package files.

Copy the above-created BPushConfig.plist, iosbdpush.h, and iosbdpush.m files to the sorted LibBPush folder

    Then package it as .zip under Windows ( the packaged name is: LibPush.zip )

    Note: It must be packaged under the window. There is a problem with the package under the mac, and the format must be zip. After the package is packaged under the mac and decompressed under the window, you will find an extra folder named __MACOSX, such as:

 

  1. 7.      Now start integrating to kony

In kony project right click Integrate Third Party Manage Custom Libraries

Add a namespace, take iosbdPush as an example

add a class

Add class details

Frameworks in the picture above: The third-party frameworks cited by Apple, Baidu Push needs to use the four frameworks Foundation.framework, CoreTelephony.framework, SystemConfiguration.framework, libz.dylib, but our project already includes three of them, so Just add CoreTelephony.framework. If you want to add multiple frameworks, you can separate them with commas " , "

    Class : It is the class we created earlier. The class name created by the example is iosbdpush

    Method : static method, refer to +(id)shareInstance in iosbdpush.m

    Add the method below:

This is just to illustrate the details that need to be paid attention to when adding methods with parameters and tape parameters, please see the following figure:

8.      Now start calling the third-party package just integrated in kony

Create a new js file in the kony project and add the following code:

//初始化百度推送
function iosbdPushinit(){
    if(appConstans.getPlatform()=="iphone"){
        var iosbdPushObject = new iosbdPush.iosbdPush();
        //Invokes method 'initBdPush' on the object
        iosbdPushObject.initBdPush();
    }
}
//获取设备的UserID和ChannelID
function iosGetUserID(){
    if(appConstans.getPlatform()=="iphone"){
        //Creates an object of class 'iosbdPush'
        var iosbdPushObject = new iosbdPush.iosbdPush();
        //Invokes method 'getUserID' on the object
        appConstans.bdPushUserID = iosbdPushObject.getUserID();
        appConstans.bdPushChannelID = iosbdPushObject.getChannelID();
        kony.print("bdPushUserID :: "+appConstans.bdPushUserID);
        kony.print("bdPushChannelID :: "+appConstans.bdPushChannelID);
    }
}
 
function oniospushsuccess(identifier){
    if(appConstans.getPlatform()=="iphone"){
        kony.print("oniospushsuccess Registered SUCCESSFULLY :"+identifier);
        var iosbdPushObject = new iosbdPush.iosbdPush();
        //Invokes method 'setIosDeviceToken' on the object
        iosbdPushObject.setIosDeviceToken(identifier);
    }
}
 
function oniospushfailure(errortable){
    kony.print("+++++oniospushfailure Registration Failed :"+JSON.stringify(errortable));
    
}
 
function onlineiospushCallback(msg){
    if(appConstans.getPlatform()=="iphone"){
        kony.print("onlineiospushCallback online:"+JSON.stringify(msg));
        //var Jmsg = JSON.stringify(msg);
        
        kony.print("msg.title"+msg.title);
        kony.print("msg.msgId"+msg.msgId);
        kony.print("msg.description"+msg.description);
        
        appConstans.pushMsgID = msg.msgId;
        if(loginStatus){   
            pushMsgPop.lblTitle.text = msg.title;
            pushMsgPop.lblDescribe.text = msg.description;
            
            pushMsgPop.show();
        }else{
            frmLogin.show();
        }   
    }
}
 
function offlineiospushCallback(msg){
    kony.print("offlineiospushCallback offline:"+JSON.stringify(msg));
}
 
function oniospushderegsuccess(){
    kony.print("oniospushderegsuccess Deregistered Successfully :");
    alert("oniospushderegsuccess=="+msg);
}
 
function oniospushderegfailure(errortable){
    kony.print("oniospushderegfailure Deregistration Failed");
    alert("oniospushderegfailure=="+msg);
}
//注册设备
function iosdevicepushInit(){
    kony.print("iospushInit begin");
    var Object = { onsuccessfulregistration:oniospushsuccess ,//注册成功
                   onfailureregistration:oniospushfailure , //注册失败
                   onlinenotification:onlineiospushCallback ,//应用这在运行
                   offlinenotification:offlineiospushCallback ,//应用未运行或后台挂起状态
                   onsuccessfulderegistration:oniospushderegsuccess ,
                   onfailurederegistration:oniospushderegfailure
        };
    if(appConstans.getPlatform()=="iphone"){
        kony.push.setCallbacks(Object);    
        var config=[0,1,2];
        kony.push.register(config);
    }
    kony.print("iospushInit end");
}

集成到此就OK了,不明白的地方可以百度,也可以加我QQ或者留言交流!如有错误欢迎大家指正。。

本帖只做技术交流~~~!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325629539&siteId=291194637
Recommended