Unity编译到Xcode自动添加文件及代码修改

原创 2015年07月10日 17:07:22

1、XUPorter用起来很厉害的样子!!微笑

对于修改Xcode代码的问题参考了MOMO大神的代码:http://www.xuanyusong.com/archives/2720

扩展类:

<span style="font-size:14px;">using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Junfine.Debuger;

namespace UnityEditor.XCodeEditor 
{
	public class XClass
	{
		string classPath;
		public XClass(string classPath)
		{
			this.classPath = classPath;
		}
		public void Process(ArrayList classes)
		{
			foreach (object o in classes) 
			{
				Hashtable table = o as Hashtable;
				ArrayList arrr = table["replace"] as ArrayList;
				ArrayList arra = table["append"] as ArrayList;
				if(arrr!=null&&arrr.Count>0)
				{
					XCodeClass xcc=new XCodeClass(classPath+table["name"]);	
					xcc.Replace(arrr[0].ToString(),arrr[1].ToString(),arrr[2].ToString());
				}
				if(arra!=null&&arra.Count>0)
				{
					XCodeClass xcc=new XCodeClass(classPath+table["name"]);	
					xcc.WriteLine(arra[0].ToString(),arra[1].ToString());
				}
			}
		}
	}
	public class XCodeClass
	{
		string path;
		public XCodeClass(string path)
		{
			this.path = path;
			Debuger.Log ("Class path:" + path);
		}
		public void WriteLine(string last,string append)
		{
			if (!File.Exists (path)) 
			{
				Debuger.Log("未找到类文件:"+path);
				return;
			}
			StreamReader streamReader = new StreamReader(path);
			string text_all = streamReader.ReadToEnd();
			streamReader.Close();
			
			int beginIndex = text_all.IndexOf(last);
			if(beginIndex == -1)
			{
				Debug.LogError(path +"中没有找到标致"+last);
				return; 
			}
			
			int endIndex = text_all.LastIndexOf("\n", beginIndex + last.Length);
			
			text_all = text_all.Substring(0, endIndex) + "\n"+append+"\n" + text_all.Substring(endIndex);
			
			StreamWriter streamWriter = new StreamWriter(path);
			streamWriter.Write(text_all);
			streamWriter.Close();
		}
		public void Replace(string oldStr,string newStr,string method="")
		{
			if (!File.Exists (path)) 
			{
				Debuger.Log("未找到类文件:"+path);
				return;
			}
			bool getMethod = false;
			string[] codes = File.ReadAllLines (path);
			for (int i=0; i<codes.Length; i++) 
			{
				string str=codes[i].ToString();
				if(string.IsNullOrEmpty(method))
				{
					if(str.Contains(oldStr))codes.SetValue(newStr,i);
				}
				else
				{
					if(!getMethod)
					{
						getMethod=str.Contains(method);
					}
					if(!getMethod)continue;
					if(str.Contains(oldStr))
					{
						codes.SetValue(newStr,i);
						break;
					}
				}
			}
			File.WriteAllLines (path, codes);
		}
	}
}</span><span style="font-size:18px;">
</span>

2、自己定义的JSON:XCExtention.projmods。

<span style="font-size:14px;">{
    "group": "XCExtention",
    "libs": ["libz.dylib","libsqlite3.0.dylib"],
    "frameworks": ["StoreKit.framework"],
    "headerpaths": ["iOS/"],
    "files":   [],
    "folders": ["Editor/XUPorter/Mods/iOS/"],
    "linker_flags": [],
    "compiler_flags": [],
    "plist":{"CFBundleIdentifier":"com.xx.xx.xx","urltype":[{"name":"weixin","schemes":["xxxxxxxxxxxxxxxx"]}]},
    "excludes": ["^.*.meta$", "^.*.mdown$", "^.*.pdf$","^.*.DS_Store"],
    "class":[{"name":"main.mm","replace":["const char* AppControllerClassName = \"UnityAppController\";","const char* Ap<span style="white-space:pre">	</span>pControllerClassName = \"UnityAppController_Custom\";",""],"apend":[]}]
}</span>
3、重写了UnityAppController.h文件:

<span style="font-size:14px;">//
//  UnityAppController_Custom.h
//  Unity-iPhone
//
//  Created by niko on 15-7-10.
//
//
#import "WeiXin/WXApi.h"

#define WeiXinID @"wx..............."
#define WeiXinSecret @"5ace7e016a14e913478cdc4219ace9e7"
#define ksendAuthRequestNotification @"ksendAuthRequestNotification"
#define GameObjectName "AndriodClass"
#define MethodName "Weixincallback_LoginSuccess"
#define ShareMethod "Weixincallback_shareSuccess"

#import "UnityAppController.h"

@interface UnityAppController_Custom:UnityAppController

@end</span>
4、接着重写UnityAppController.m文件(主要实现了微信的登录和分享功能微笑):

<span style="font-size:14px;">//
//  UnityAppController_Custom.m
//  Unity-iPhone
//
//  Created by niko on 15-7-10.
//
//

#import <Foundation/Foundation.h>
#import "UnityAppController_Custom.h"

#if defined (__cplusplus)
extern "C"
{
#endif
    bool isWXAppInstalled()
    {
        return [WXApi isWXAppInstalled];
    }
    bool isWXAppSupportApi()
    {
        return [WXApi isWXAppSupportApi];
    }
    // 给Unity3d调用的方法
    void weixinLoginByIos()
    {
        // 登录
        [[NSNotificationCenter defaultCenter] postNotificationName:ksendAuthRequestNotification object:nil];
    }
    void ShareByIos(const char* title,const char*desc,const char*url)
    {
        NSString *titleStr=[NSString stringWithUTF8String:title];
        NSString *descStr=[NSString stringWithUTF8String:desc];//0416aa28b5d2ed1f3199083b3806c6bl
        NSString *urlStr=[NSString stringWithUTF8String:url];
        NSLog(@"ShareByIos titleStr:%@",titleStr);
        NSLog(@"ShareByIos descStr:%@",descStr);
        NSLog(@"ShareByIos urlStr:%@",urlStr);
        
        NSDictionary *dic=[[NSBundle mainBundle] infoDictionary];
        NSLog(@"dic:%@",dic);
        NSArray *arr=[[[dic valueForKey:@"CFBundleIcons"] valueForKey:@"CFBundlePrimaryIcon"]valueForKey:@"CFBundleIconFiles"];
        NSLog(@"arr:%@",arr);
        NSString *iconName=arr[0];
        NSLog(@"iconName:%@",iconName);
        // 分享
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = titleStr;//@"专访张小龙:产品之上的世界观";
        message.description = descStr;//@"微信的平台化发展方向是否真的会让这个原本简洁的产品变得臃肿?在国际化发展方向上,微信面临的问题真的是文化差异壁垒吗?腾讯高级副总裁、微信产品负责人张小龙给出了自己的回复。";
        [message setThumbImage:[UIImage imageNamed:iconName]];
        //        [message setThumbImage:[UIImage imageNamed:@"AppIcon72x72"]];
        
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = urlStr;//@"http://tech.qq.com/zt2012/tmtdecode/252.htm";
        
        message.mediaObject = ext;
        message.mediaTagName = @"WECHAT_TAG_SHARE";
        
        SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        [WXApi sendReq:req];
    }
#if defined (__cplusplus)
}
#endif

@implementation UnityAppController_Custom

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendAuthRequest) name:ksendAuthRequestNotification object:nil]; // 微信
    //向微信注册
    [WXApi registerApp:WeiXinID];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [super application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    return [WXApi handleOpenURL:url delegate:self];
}
#pragma mark - WXApiDelegate

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)onReq:(BaseReq *)req // 微信向第三方程序发起请求,要求第三方程序响应
{
    
}

- (void)onResp:(BaseResp *)resp // 第三方程序向微信发送了sendReq的请求,那么onResp会被回调
{
    if([resp isKindOfClass:[SendAuthResp class]]) // 登录授权
    {
        SendAuthResp *temp = (SendAuthResp*)resp;
        if(temp.code!=nil)UnitySendMessage(GameObjectName, MethodName, [temp.code cStringUsingEncoding:NSUTF8StringEncoding]);
        
        //        [self getAccessToken:temp.code];
    }
    else if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        // 分享
        if(resp.errCode==0)
        {
            NSString *code = [NSString stringWithFormat:@"%d",resp.errCode]; // 0是成功 -2是取消
            NSLog(@"SendMessageToWXResp:%@",code);
            UnitySendMessage(GameObjectName, ShareMethod, [code cStringUsingEncoding:NSUTF8StringEncoding]);
        }
    }
}
#pragma mark - Private

- (void)sendAuthRequest

{
    
    SendAuthReq* req = [[[SendAuthReq alloc] init] autorelease];
    
    req.scope = @"snsapi_userinfo";
    
    req.state = @"only123";
    
    
    
    [WXApi sendAuthReq:req viewController:_rootController delegate:self];
    
}



- (void)getAccessToken:(NSString *)code

{
    
    NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WeiXinID,WeiXinSecret,code];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     
     ^(NSURLResponse *response,NSData *data,NSError *connectionError)
     
     {
         
         if (connectionError != NULL)
             
         {
             
             
             
         }
         
         else
             
         {
             
             if (data != NULL)
                 
             {
                 
                 NSError *jsonParseError;
                 
                 NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonParseError];
                 
                 NSLog(@"#####responseData = %@",responseData);
                 
                 if (jsonParseError != NULL)
                     
                 {
                     
                     //                    NSLog(@"#####responseData = %@",jsonParseError);
                     
                 }
                 
                 NSString *accessToken = [responseData valueForKey:@"access_token"];
                 
                 NSString *openid = [responseData valueForKey:@"openid"];
                 
                 [self getUserInfo:accessToken withOpenID:openid];
                 
             }
             
         }
         
     }];
    
}



- (void)getUserInfo:(NSString *)accessToken withOpenID: (NSString *)openid

{
    
    NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openid];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     
     ^(NSURLResponse *response,NSData *data,NSError *connectionError) {
         
         if (connectionError != NULL) {
             
             
             
         } else {
             
             if (data != NULL) {
                 
                 NSError *jsonError;
                 
                 NSString *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
                 
                 NSLog(@"#####responseData = %@",responseData);
                 
                 NSString *jsonData = [NSString stringWithFormat:@"%@",responseData];
                 
                 UnitySendMessage(GameObjectName, MethodName, [jsonData cStringUsingEncoding:NSUTF8StringEncoding]);
                 
                 if (jsonError != NULL) {
                     
                     //                     NSLog(@"#####responseData = %@",jsonError);
                     
                 }
                 
             }
             
         }
         
     }];
    
}

#pragma mark -

@end</span>
4、这里是Unity里面得目录:


5、然后到XCode目录就成这样啦:


6、最后剩下一个问题:怎么实现自动添加AppIcon?

版权声明:本文为博主原创文章,未经博主允许不得转载。

关于unity导出xcode的工程中unity的内容部分。备忘录

Raw文件夹下是一些资源文件。 不能替换部分为 1.PlayerConnectionConfigFile 文件                           2.Managed 文件夹     ...

Unity读取IOS平台文件

本例测试在IOS端读取 .txt 文件 在开发时,需要在IOS端读取的文件文件一定要放在 “StreamingAssets” 文件夹下(在安装时IOS会自动将StreamingAssets文件夹下的...

iOS开发Icon图标设置

图标是iOS程序包所必需的组成部分。如果你没有提供程序所需的各种尺寸的图标,程序上传发布时可能会无法通过验证。iOS程序为兼顾不同的应用场景,定义了多个不同规格的图标,并以不同的命名区分: iO...

【Unity3D游戏开发】App游戏名字本地化 (二七)

开发环境Unity5.3 XCode7.2目标游戏名字需要多语言处理过程1.添加多语言 2.用CFBundleDisplayName来处理名字多语言 失败尝试流程1.未成功 info.plist...

unity ios应用名称多语言本地化

详细流程这个文章讲的特别清楚了,Xcode7以上本地化(localization) 而对于unity打包后的xcode项目,有一步骤要特别注意的,不然会报错,如下图将Bundle display n...

iOS-支付宝&微信支付

一. 微信支付 1.所需要的材料 微信SDK 微信SDK在微信开放平台上面申请得到的参数 // 应用的APPID kWXAppID @"wxc82cXXXXXXXX" //...

【Unity 3D学习】获取鼠标滑动方向(上下左右)-控制摄像机围绕物体旋转

using UnityEngine; using System.Collections; public class ModelRotationScript : MonoBehaviour { p...

Unity编译至Xcode工程后自动添加文件和库的方法

XUPorter项目Github链接 为什么想要自动添加 由于Unity是全平台的游戏开发环境,在开发中针对特定平台的特定功能时,很难避免根据对象平台的不同而引入不同的依赖。包括源码,需要的库...

Unity编译至Xcode工程后自动添加文件和库的方法

XUPorter项目Github链接 为什么想要自动添加 由于Unity是全平台的游戏开发环境,在开发中针对特定平台的特定功能时,很难避免根据对象平台的不同而引入不同的依赖。包括源码,需要的库和框...
  • cbbbc
  • cbbbc
  • 2015年12月30日 20:41
  • 1317

Unity编译至Xcode工程后自动添加文件和库的方法

为什么想要自动添加 由于Unity是全平台的游戏开发环境,在开发中针对特定平台的特定功能时,很难避免根据对象平台的不同而引入不同的依赖。包括源码,需要的库和框架等。在使用各种插件后这种情况愈发严重:...
  • cubesky
  • cubesky
  • 2014年08月22日 11:54
  • 718
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Unity编译到Xcode自动添加文件及代码修改
举报原因:
原因补充:

(最多只允许输入30个字)