关闭

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

标签: IOSunityxcodesdk
1715人阅读 评论(0) 收藏 举报

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?

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:50931次
    • 积分:699
    • 等级:
    • 排名:千里之外
    • 原创:18篇
    • 转载:9篇
    • 译文:0篇
    • 评论:11条
    最新评论