1. 程式人生 > >Unity+百度推送+IOS版

Unity+百度推送+IOS版

2.Untiy部分設定:

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

2.在Unity上新增PushManager物件。

3.Unity程式碼呼叫Object-C函式實現新增Tag和刪除Tag程式碼,並將指令碼新增到PushManager物件上:

#ifUNITY_IPHONE
[DllImport("__Internal")]
publicstaticexternvoid__setTag(stringtag);
[DllImport("__Internal")]
publicstaticexternvoid__delTag(string

tag);

publicstaticvoidBind(){

}
publicstaticvoidSetTag(stringtag)
{
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);
}
publicstaticvoiddelTag(stringtag){
__delTag(tag);
}
#endif

再寫一個類簡單呼叫介面:

voidmessage(stringstr)//用於接收Object-c返回的資料
{
Receive=str;
}

voidSetTag(stringtag){
BaiDuPushSDK.SetTag(tag);
}

    voidDelTag(stringtag){
BaiDuPushSDK.delTag(tag);
}

   4.到這裡Unity的設定和程式碼部分就已經完成,然和釋出Xcode工程。

3.Xcode工程部分:

2.百度推送應用中新增該推送證書:

3.Xcode環境設定

選擇開發team

在除錯開發模式的推送時,在配置Xcode TRGETS Build Setting 中的Provisioning Profile 時需要手動指定包含推送功能的證書。


4.程式碼部分設定:標頭檔案:#import "BPush.h",開啟UnityAppController.mm檔案找到函式:

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

[KeyboardDelegateInitialize];後新增如下程式碼。

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
	::printf("-> applicationDidFinishLaunching()\n");

	// send notfications
#if !UNITY_TVOS
	if(UILocalNotification* notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey])
		UnitySendLocalNotification(notification);

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

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

	UnityInitApplicationNoGraphics([[[NSBundle mainBundle] bundlePath] UTF8String]);

	[self selectRenderingAPI];
	[UnityRenderingView InitializeForAPI:self.renderingAPI];

	_window			= [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
	_unityView		= [self createUnityView];

	[DisplayManager Initialize];
	_mainDisplay	= [DisplayManager Instance].mainDisplay;
	[_mainDisplay createWithWindow:_window andView:_unityView];

	[self createUI];
	[self preStartUnity];

	// if you wont use keyboard you may comment it out at save some memory
	[KeyboardDelegate Initialize];
    //-------------------- Push -----------------------------
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
        // 8.0
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        // ~> 7.1
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
#warning 測試 開發環境 時需要修改BPushMode為BPushModeDevelopment 需要修改Apikey為自己的Apikey
#warning 上線 AppStore 時需要修改BPushMode為BPushModeProduction 需要修改Apikey為自己的Apikey

    // 在 App 啟動時註冊百度雲推送服務,需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"百度推送的apiKey" pushMode:BPushModeDevelopment withFirstAction:@"開啟" withSecondAction:@"回覆" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
    // App 是使用者點選推送訊息啟動
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }
#if TARGET_IPHONE_SIMULATOR
    Byte dt[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};
    [self application:application didRegisterForRemoteNotificationsWithDeviceToken:[NSData dataWithBytes:dt length:32]];
#endif
    //角標清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    

	return YES;
}


5.- (void)applicationDidBecomeActive:(UIApplication*)application 函式中新增清除角標程式碼
//角標清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

6.- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken 函式中新增如下程式碼

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken");
    NSLog(@"test:%@",deviceToken);
    NSLog(@"test  繫結成功");
    
    
    //角標清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        // 需要在繫結成功後進行 settag listtag deletetag unbind 操作否則會失敗
        
        // 網路錯誤
        if (error) {
            NSLog(@"test  繫結失敗@",error);
            return ;
        }
        if (result) {
            // 確認繫結成功
            if ([result[@"error_code"]intValue]!=0) {
                
                NSString *myChannel_id =[NSString stringWithFormat:@"{\"state\":\"Bind\",\"errorCode\":\"1\"}"];
                NSLog(@"==%@",myChannel_id);
                UnitySendMessage("PushManager","message",[myChannel_id UTF8String]);
                NSLog(@"test  繫結失敗");
                return;
            }
            // 獲取channel_id
            NSString *myChannel_id =[BPush getChannelId];
            myChannel_id=[NSString stringWithFormat:@"{\"state\":\"Bind\",\"errorCode\":\"0\",\"channelId\":\"%@\"}",myChannel_id];
            NSLog(@"==%@",myChannel_id);
            UnitySendMessage("PushManager","message",[myChannel_id UTF8String]);
        }
    }];
    AppController_SendNotificationWithArg(kUnityDidRegisterForRemoteNotificationsWithDeviceToken, deviceToken);
    
    UnitySendDeviceToken(deviceToken);
}


7.新增如下函式和標頭檔案:#import "BPush.h"
extern "C" {
    void __setTag(const char* tag){
        NSString *tagstr=[NSString stringWithUTF8String:tag];
        [BPush setTag:tagstr withCompleteHandler:^(id result, NSError *error) {
            if (result) {
                NSLog(@"設定tag成功");
                 UnitySendMessage("PushManager","massage","設定tag成功");
            }
        }];
    }
    void __delTag(const char* tag){
        NSString *tagstr=[NSString stringWithUTF8String:tag];
        [BPush delTag:tagstr withCompleteHandler:^(id result, NSError *error) {
            if (result) {
                NSLog(@"刪除tag成功");
                UnitySendMessage("PushManager","massage","刪除tag成功");
            }
        }];
        
    }
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    // 此處可以根據 notificationSettings 引數判斷應用當前所被允許的推送型別
    // 應用程式註冊推送功能,以獲取當前 App 的 deviceToken
    [application registerForRemoteNotifications];
}
<pre name="code" class="objc">// 此方法是 使用者點選了通知,應用在前臺 或者開啟後臺並且應用在後臺 時調起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    // 列印到日誌 textView 中
    NSLog(@"********** iOS7.0之後 background **********");
    // 應用在前臺,不跳轉頁面,讓使用者選擇。
    if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"acitve ");
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一條訊息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
        [alertView show];
    }
    NSString* Receive=[NSString stringWithFormat:@"{\"state\":\"Receiver\",\"title\":\"\",\"description\":\"%@\"}",userInfo[@"aps"][@"alert"]];
    NSLog(@"==%@",Receive);
    UnitySendMessage("PushManager","message",[Receive UTF8String]);

    
    NSLog(@"此方法是 使用者點選了通知,應用在前臺 或者開啟後臺並且應用在後臺 時調起%@",userInfo[@"aps"][@"alert"]);
}