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?

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

Unity3D 嵌入iOS原生代码,并实现unity iOS之间的交互

参考链接点击打开链接 https://the-nerd.be/2014/08/06/add-unity3d-in-a-native-ios-application/ UnityAppCont...
  • chuan403082010
  • chuan403082010
  • 2017年03月17日 05:31
  • 4484

自动修改 Unity3d 导出的 Xcode 项目

在 Unity3d 导出 iOS 项目后,常常需要定制一些选项,例如指定额外的 framework,修改 Info.plist 等。Unity3d 在导出工程的时候提供两个选项:替换整个项目「repl...
  • yinhuaiya
  • yinhuaiya
  • 2017年03月31日 14:55
  • 1028

Unity5.1 创建IOS的Xcode项目. 如何手动增量更新应用的资源和代码.

Unity开发IOS还是比较烦人的. 就算是用Mac也比较烦人.因为要生成xcode项目.而且你还需要在xcode里面接入sdk啥的. 所以非常的某乱. 经过洒家的研究.终于发现了一些生成项目的关心....
  • spiritring
  • spiritring
  • 2015年06月26日 17:04
  • 4348

unity 编译后执行,自动配置 Xcode 项目的方法

unity中,实现编译后继续操作Xcode文件夹的主要方法是使用 PostProcessBuildAttribute官方文档: https://docs.unity3d.com/ScriptRef...
  • WPAPA
  • WPAPA
  • 2016年09月28日 12:15
  • 1024

Unity iOS打开AppStore评星页面,浅谈Application.OpenURL()方法。

Unity iOS打开AppStore评星页面,浅谈Application.OpenURL()方法。 Posted in  Unity on August 6, 2013Comments: 暂无...
  • EasonEasonEasonEason
  • EasonEasonEasonEason
  • 2017年03月22日 13:41
  • 510

iOS将Unity导出的Xcode工程导入到另一个Xcode项目, 及常见报错的解决方法

demo下载地址 http://pan.baidu.com/s/1pLcpKpl 1.Unity导出工程时设置bundle id要与项目一致 2.修改bit c...
  • dylan_lwb_
  • dylan_lwb_
  • 2016年05月19日 13:02
  • 10994

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

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

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

1、XUPorter用起来很厉害的样子!! 对于修改Xcode代码的问题参考了MOMO大神的代码:http://www.xuanyusong.com/archives/2720。 扩展类: us...
  • h5q8n2e7
  • h5q8n2e7
  • 2015年07月10日 17:07
  • 2051

Unity编译到Xcode自动添加AppIcon

1、将要添加的所有Icon放到指定目录: 2、拷贝Icon的方法: public static void CopyIcons(string pathToBuiltProject) { ...
  • h5q8n2e7
  • h5q8n2e7
  • 2015年07月14日 17:39
  • 1239

Unity成功导出Xcode工程后自动修改一些设置

最近用Unity接ios的sdk,用Unity导出Xcode工程后,由于刚刚开始,每次都是手动设置。后来看了Unity3D研究院之IOS全自动编辑framework、plist、oc代码(六十七)和U...
  • qq_33461689
  • qq_33461689
  • 2018年01月09日 10:07
  • 94
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Unity编译到Xcode自动添加文件及代码修改
举报原因:
原因补充:

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