您的位置:首页 > 移动开发 > Unity3D

Unity+百度推送+IOS版

2016-04-05 18:46 519 查看
1.下载百度云推送SDK

2.Untiy部分设置:

1.把SDK中idfaversion下的BPush.h和libBpush.a放入Unity中的Plugins/IOS/下

2.在Unity上添加PushManager对象。

3.Unity代码调用Object-C函数实现添加Tag和删除Tag代码,并将脚本添加到PushManager对象上:

#if UNITY_IPHONE
    [DllImport ("__Internal")]
    public static extern void __setTag (string tag);
    [DllImport ("__Internal")]
    public static extern void __delTag (string tag);

     public static void Bind() {
        
    }
    public static void SetTag(string tag)
    {
        if (!PlayerPrefs.HasKey("PushTag"))
        {
            PlayerPrefs.SetString("PushTag", tag);
            Debug.Log("SetTag:"+ __setTag( tag));
            return;
        }
        if (PlayerPrefs.GetString("PushTag") == tag)
        {
            return;
        }
        else
        {
            Debug.Log("DelTag:"+ __delTag(PlayerPrefs.GetString("PushTag")));
            PlayerPrefs.SetString("PushTag", tag);
        }
        __setTag(tag);
    }
    public static void delTag(string tag){
        __delTag (tag);
    }
#endif

再写一个类简单调用接口:

 void message(string str)//用于接收Object-c返回的数据
    {
        Receive = str;
    }
  
    void SetTag(string tag) {
        BaiDuPushSDK.SetTag(tag);
    }

  void DelTag(string tag){
        BaiDuPushSDK.delTag (tag);
    }

  4.到这里Unity的设置和代码部分就已经完成,然和发布Xcode工程。

3.Xcode工程部分:

1.申请推送证书:参考百度云推送官网

2.百度推送应用中添加该推送证书:

3.Xcode环境设置

选择开发team



在调试开发模式的推送时,在配置XcodeTRGETSBuildSetting中的ProvisioningProfile时需要手动指定包含推送功能的证书。



4.代码部分设置:头文件:#import "BPush.h",打开UnityAppController.mm文件找到函数:

-(BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions函数中

[KeyboardDelegateInitialize];后添加如下代码。
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
::printf("->applicationDidFinishLaunching()\n");

//sendnotfications
#if!UNITY_TVOS
if(UILocalNotification*notification=[launchOptionsobjectForKey:UIApplicationLaunchOptionsLocalNotificationKey])
UnitySendLocalNotification(notification);

if(NSDictionary*notification=[launchOptionsobjectForKey:UIApplicationLaunchOptionsRemoteNotificationKey])
UnitySendRemoteNotification(notification);

if([UIDevicecurrentDevice].generatesDeviceOrientationNotifications==NO)
[[UIDevicecurrentDevice]beginGeneratingDeviceOrientationNotifications];
#endif

UnityInitApplicationNoGraphics([[[NSBundlemainBundle]bundlePath]UTF8String]);

[selfselectRenderingAPI];
[UnityRenderingViewInitializeForAPI:self.renderingAPI];

_window =[[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];
_unityView =[selfcreateUnityView];

[DisplayManagerInitialize];
_mainDisplay =[DisplayManagerInstance].mainDisplay;
[_mainDisplaycreateWithWindow:_windowandView:_unityView];

[selfcreateUI];
[selfpreStartUnity];

//ifyouwontusekeyboardyoumaycommentitoutatsavesomememory
[KeyboardDelegateInitialize];
//--------------------Push-----------------------------
if(floor(NSFoundationVersionNumber)>NSFoundationVersionNumber_iOS_7_1){
//8.0
UIUserNotificationTypemyTypes=UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound;
UIUserNotificationSettings*settings=[UIUserNotificationSettingssettingsForTypes:myTypescategories:nil];
[[UIApplicationsharedApplication]registerUserNotificationSettings:settings];
}else{
//~>7.1
UIRemoteNotificationTypemyTypes=UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
[[UIApplicationsharedApplication]registerForRemoteNotificationTypes:myTypes];
}

#warning测试开发环境时需要修改BPushMode为BPushModeDevelopment需要修改Apikey为自己的Apikey
#warning上线AppStore时需要修改BPushMode为BPushModeProduction需要修改Apikey为自己的Apikey

//在App启动时注册百度云推送服务,需要提供Apikey
[BPushregisterChannel:launchOptionsapiKey:@"百度推送的apiKey"pushMode:BPushModeDevelopmentwithFirstAction:@"打开"withSecondAction:@"回复"withCategory:@"test"useBehaviorTextInput:YESisDebug:YES];
//App是用户点击推送消息启动
NSDictionary*userInfo=[launchOptionsobjectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo){
[BPushhandleNotification:userInfo];
}
#ifTARGET_IPHONE_SIMULATOR
Bytedt[32]={0xc6,0x1e,0x5a,0x13,0x2d,0x04,0x83,0x82,0x12,0x4c,0x26,0xcd,0x0c,0x16,0xf6,0x7c,0x74,0x78,0xb3,0x5f,0x6b,0x37,0x0a,0x42,0x4f,0xe7,0x97,0xdc,0x9f,0x3a,0x54,0x10};
[selfapplication:applicationdidRegisterForRemoteNotificationsWithDeviceToken:[NSDatadataWithBytes:dtlength:32]];
#endif
//角标清0 [[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];

returnYES;
}

5.-(void)applicationDidBecomeActive:(UIApplication*)application
函数中添加清除角标代码

//角标清0
[[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];


  6.-(void)application:(UIApplication*)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
函数中添加如下代码

-(void)application:(UIApplication*)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken");
NSLog(@"test:%@",deviceToken);
NSLog(@"test绑定成功");

//角标清0 [[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];

[BPushregisterDeviceToken:deviceToken];
[BPushbindChannelWithCompleteHandler:^(idresult,NSError*error){
//需要在绑定成功后进行settaglisttagdeletetagunbind操作否则会失败

//网络错误
if(error){
NSLog(@"test绑定失败@",error);
return;
}
if(result){
//确认绑定成功
if([result[@"error_code"]intValue]!=0){

NSString*myChannel_id=[NSStringstringWithFormat:@"{\"state\":\"Bind\",\"errorCode\":\"1\"}"];
NSLog(@"==%@",myChannel_id);
UnitySendMessage("PushManager","message",[myChannel_idUTF8String]);
NSLog(@"test绑定失败");
return;
}
//获取channel_id
NSString*myChannel_id=[BPushgetChannelId];
myChannel_id=[NSStringstringWithFormat:@"{\"state\":\"Bind\",\"errorCode\":\"0\",\"channelId\":\"%@\"}",myChannel_id];
NSLog(@"==%@",myChannel_id);
UnitySendMessage("PushManager","message",[myChannel_idUTF8String]);
}
}];
AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken,deviceToken);

UnitySendDeviceToken(deviceToken);
}




7.添加如下函数和头文件:#import
"BPush.h"

extern"C"{
void__setTag(constchar*tag){
NSString*tagstr=[NSStringstringWithUTF8String:tag];
[BPushsetTag:tagstrwithCompleteHandler:^(idresult,NSError*error){
if(result){
NSLog(@"设置tag成功");
UnitySendMessage("PushManager","massage","设置tag成功");
}
}];
}
void__delTag(constchar*tag){
NSString*tagstr=[NSStringstringWithUTF8String:tag];
[BPushdelTag:tagstrwithCompleteHandler:^(idresult,NSError*error){
if(result){
NSLog(@"删除tag成功");
UnitySendMessage("PushManager","massage","删除tag成功");
}
}];

}
}
-(void)application:(UIApplication*)applicationdidRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings
{
//此处可以根据notificationSettings参数判断应用当前所被允许的推送类型
//应用程序注册推送功能,以获取当前App的deviceToken
[applicationregisterForRemoteNotifications];
}
<prename="code"class="objc">//此方法是用户点击了通知,应用在前台或者开启后台并且应用在后台时调起
-(void)application:(UIApplication*)applicationdidReceiveRemoteNotification:(NSDictionary*)userInfofetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler
{
completionHandler(UIBackgroundFetchResultNewData);
//打印到日志textView中
NSLog(@"**********iOS7.0之后background**********");
//应用在前台,不跳转页面,让用户选择。
if(application.applicationState==UIApplicationStateActive){
NSLog(@"acitve");
UIAlertView*alertView=[[UIAlertViewalloc]initWithTitle:@"收到一条消息"message:userInfo[@"aps"][@"alert"]delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
[alertViewshow];
}
NSString*Receive=[NSStringstringWithFormat:@"{\"state\":\"Receiver\",\"title\":\"\",\"description\":\"%@\"}",userInfo[@"aps"][@"alert"]];
NSLog(@"==%@",Receive);
UnitySendMessage("PushManager","message",[ReceiveUTF8String]);

NSLog(@"此方法是用户点击了通知,应用在前台或者开启后台并且应用在后台时调起%@",userInfo[@"aps"][@"alert"]);
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: