当前位置:   article > 正文

Unity编译到Xcode自动添加文件及代码修改_unityeditor.ios.xcode addfile

unityeditor.ios.xcode addfile

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

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

扩展类:

  1. <span style="font-size:14px;">using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Junfine.Debuger;
  6. namespace UnityEditor.XCodeEditor
  7. {
  8. public class XClass
  9. {
  10. string classPath;
  11. public XClass(string classPath)
  12. {
  13. this.classPath = classPath;
  14. }
  15. public void Process(ArrayList classes)
  16. {
  17. foreach (object o in classes)
  18. {
  19. Hashtable table = o as Hashtable;
  20. ArrayList arrr = table["replace"] as ArrayList;
  21. ArrayList arra = table["append"] as ArrayList;
  22. if(arrr!=null&&arrr.Count>0)
  23. {
  24. XCodeClass xcc=new XCodeClass(classPath+table["name"]);
  25. xcc.Replace(arrr[0].ToString(),arrr[1].ToString(),arrr[2].ToString());
  26. }
  27. if(arra!=null&&arra.Count>0)
  28. {
  29. XCodeClass xcc=new XCodeClass(classPath+table["name"]);
  30. xcc.WriteLine(arra[0].ToString(),arra[1].ToString());
  31. }
  32. }
  33. }
  34. }
  35. public class XCodeClass
  36. {
  37. string path;
  38. public XCodeClass(string path)
  39. {
  40. this.path = path;
  41. Debuger.Log ("Class path:" + path);
  42. }
  43. public void WriteLine(string last,string append)
  44. {
  45. if (!File.Exists (path))
  46. {
  47. Debuger.Log("未找到类文件:"+path);
  48. return;
  49. }
  50. StreamReader streamReader = new StreamReader(path);
  51. string text_all = streamReader.ReadToEnd();
  52. streamReader.Close();
  53. int beginIndex = text_all.IndexOf(last);
  54. if(beginIndex == -1)
  55. {
  56. Debug.LogError(path +"中没有找到标致"+last);
  57. return;
  58. }
  59. int endIndex = text_all.LastIndexOf("\n", beginIndex + last.Length);
  60. text_all = text_all.Substring(0, endIndex) + "\n"+append+"\n" + text_all.Substring(endIndex);
  61. StreamWriter streamWriter = new StreamWriter(path);
  62. streamWriter.Write(text_all);
  63. streamWriter.Close();
  64. }
  65. public void Replace(string oldStr,string newStr,string method="")
  66. {
  67. if (!File.Exists (path))
  68. {
  69. Debuger.Log("未找到类文件:"+path);
  70. return;
  71. }
  72. bool getMethod = false;
  73. string[] codes = File.ReadAllLines (path);
  74. for (int i=0; i<codes.Length; i++)
  75. {
  76. string str=codes[i].ToString();
  77. if(string.IsNullOrEmpty(method))
  78. {
  79. if(str.Contains(oldStr))codes.SetValue(newStr,i);
  80. }
  81. else
  82. {
  83. if(!getMethod)
  84. {
  85. getMethod=str.Contains(method);
  86. }
  87. if(!getMethod)continue;
  88. if(str.Contains(oldStr))
  89. {
  90. codes.SetValue(newStr,i);
  91. break;
  92. }
  93. }
  94. }
  95. File.WriteAllLines (path, codes);
  96. }
  97. }
  98. }</span><span style="font-size:18px;">
  99. </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文件:

  1. <span style="font-size:14px;">//
  2. // UnityAppController_Custom.h
  3. // Unity-iPhone
  4. //
  5. // Created by niko on 15-7-10.
  6. //
  7. //
  8. #import "WeiXin/WXApi.h"
  9. #define WeiXinID @"wx..............."
  10. #define WeiXinSecret @"5ace7e016a14e913478cdc4219ace9e7"
  11. #define ksendAuthRequestNotification @"ksendAuthRequestNotification"
  12. #define GameObjectName "AndriodClass"
  13. #define MethodName "Weixincallback_LoginSuccess"
  14. #define ShareMethod "Weixincallback_shareSuccess"
  15. #import "UnityAppController.h"
  16. @interface UnityAppController_Custom:UnityAppController
  17. @end</span>
4、接着重写UnityAppController.m文件(主要实现了微信的登录和分享功能微笑):

  1. <span style="font-size:14px;">//
  2. // UnityAppController_Custom.m
  3. // Unity-iPhone
  4. //
  5. // Created by niko on 15-7-10.
  6. //
  7. //
  8. #import <Foundation/Foundation.h>
  9. #import "UnityAppController_Custom.h"
  10. #if defined (__cplusplus)
  11. extern "C"
  12. {
  13. #endif
  14. bool isWXAppInstalled()
  15. {
  16. return [WXApi isWXAppInstalled];
  17. }
  18. bool isWXAppSupportApi()
  19. {
  20. return [WXApi isWXAppSupportApi];
  21. }
  22. // 给Unity3d调用的方法
  23. void weixinLoginByIos()
  24. {
  25. // 登录
  26. [[NSNotificationCenter defaultCenter] postNotificationName:ksendAuthRequestNotification object:nil];
  27. }
  28. void ShareByIos(const char* title,const char*desc,const char*url)
  29. {
  30. NSString *titleStr=[NSString stringWithUTF8String:title];
  31. NSString *descStr=[NSString stringWithUTF8String:desc];//0416aa28b5d2ed1f3199083b3806c6bl
  32. NSString *urlStr=[NSString stringWithUTF8String:url];
  33. NSLog(@"ShareByIos titleStr:%@",titleStr);
  34. NSLog(@"ShareByIos descStr:%@",descStr);
  35. NSLog(@"ShareByIos urlStr:%@",urlStr);
  36. NSDictionary *dic=[[NSBundle mainBundle] infoDictionary];
  37. NSLog(@"dic:%@",dic);
  38. NSArray *arr=[[[dic valueForKey:@"CFBundleIcons"] valueForKey:@"CFBundlePrimaryIcon"]valueForKey:@"CFBundleIconFiles"];
  39. NSLog(@"arr:%@",arr);
  40. NSString *iconName=arr[0];
  41. NSLog(@"iconName:%@",iconName);
  42. // 分享
  43. WXMediaMessage *message = [WXMediaMessage message];
  44. message.title = titleStr;//@"专访张小龙:产品之上的世界观";
  45. message.description = descStr;//@"微信的平台化发展方向是否真的会让这个原本简洁的产品变得臃肿?在国际化发展方向上,微信面临的问题真的是文化差异壁垒吗?腾讯高级副总裁、微信产品负责人张小龙给出了自己的回复。";
  46. [message setThumbImage:[UIImage imageNamed:iconName]];
  47. // [message setThumbImage:[UIImage imageNamed:@"AppIcon72x72"]];
  48. WXWebpageObject *ext = [WXWebpageObject object];
  49. ext.webpageUrl = urlStr;//@"http://tech.qq.com/zt2012/tmtdecode/252.htm";
  50. message.mediaObject = ext;
  51. message.mediaTagName = @"WECHAT_TAG_SHARE";
  52. SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
  53. req.bText = NO;
  54. req.message = message;
  55. req.scene = WXSceneTimeline;
  56. [WXApi sendReq:req];
  57. }
  58. #if defined (__cplusplus)
  59. }
  60. #endif
  61. @implementation UnityAppController_Custom
  62. -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  63. {
  64. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendAuthRequest) name:ksendAuthRequestNotification object:nil]; // 微信
  65. //向微信注册
  66. [WXApi registerApp:WeiXinID];
  67. return [super application:application didFinishLaunchingWithOptions:launchOptions];
  68. }
  69. -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  70. {
  71. [super application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
  72. return [WXApi handleOpenURL:url delegate:self];
  73. }
  74. #pragma mark - WXApiDelegate
  75. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  76. {
  77. return [WXApi handleOpenURL:url delegate:self];
  78. }
  79. - (void)onReq:(BaseReq *)req // 微信向第三方程序发起请求,要求第三方程序响应
  80. {
  81. }
  82. - (void)onResp:(BaseResp *)resp // 第三方程序向微信发送了sendReq的请求,那么onResp会被回调
  83. {
  84. if([resp isKindOfClass:[SendAuthResp class]]) // 登录授权
  85. {
  86. SendAuthResp *temp = (SendAuthResp*)resp;
  87. if(temp.code!=nil)UnitySendMessage(GameObjectName, MethodName, [temp.code cStringUsingEncoding:NSUTF8StringEncoding]);
  88. // [self getAccessToken:temp.code];
  89. }
  90. else if([resp isKindOfClass:[SendMessageToWXResp class]])
  91. {
  92. // 分享
  93. if(resp.errCode==0)
  94. {
  95. NSString *code = [NSString stringWithFormat:@"%d",resp.errCode]; // 0是成功 -2是取消
  96. NSLog(@"SendMessageToWXResp:%@",code);
  97. UnitySendMessage(GameObjectName, ShareMethod, [code cStringUsingEncoding:NSUTF8StringEncoding]);
  98. }
  99. }
  100. }
  101. #pragma mark - Private
  102. - (void)sendAuthRequest
  103. {
  104. SendAuthReq* req = [[[SendAuthReq alloc] init] autorelease];
  105. req.scope = @"snsapi_userinfo";
  106. req.state = @"only123";
  107. [WXApi sendAuthReq:req viewController:_rootController delegate:self];
  108. }
  109. - (void)getAccessToken:(NSString *)code
  110. {
  111. NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WeiXinID,WeiXinSecret,code];
  112. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
  113. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  114. [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
  115. ^(NSURLResponse *response,NSData *data,NSError *connectionError)
  116. {
  117. if (connectionError != NULL)
  118. {
  119. }
  120. else
  121. {
  122. if (data != NULL)
  123. {
  124. NSError *jsonParseError;
  125. NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonParseError];
  126. NSLog(@"#####responseData = %@",responseData);
  127. if (jsonParseError != NULL)
  128. {
  129. // NSLog(@"#####responseData = %@",jsonParseError);
  130. }
  131. NSString *accessToken = [responseData valueForKey:@"access_token"];
  132. NSString *openid = [responseData valueForKey:@"openid"];
  133. [self getUserInfo:accessToken withOpenID:openid];
  134. }
  135. }
  136. }];
  137. }
  138. - (void)getUserInfo:(NSString *)accessToken withOpenID: (NSString *)openid
  139. {
  140. NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openid];
  141. NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
  142. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  143. [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
  144. ^(NSURLResponse *response,NSData *data,NSError *connectionError) {
  145. if (connectionError != NULL) {
  146. } else {
  147. if (data != NULL) {
  148. NSError *jsonError;
  149. NSString *responseData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
  150. NSLog(@"#####responseData = %@",responseData);
  151. NSString *jsonData = [NSString stringWithFormat:@"%@",responseData];
  152. UnitySendMessage(GameObjectName, MethodName, [jsonData cStringUsingEncoding:NSUTF8StringEncoding]);
  153. if (jsonError != NULL) {
  154. // NSLog(@"#####responseData = %@",jsonError);
  155. }
  156. }
  157. }
  158. }];
  159. }
  160. #pragma mark -
  161. @end</span>
4、这里是Unity里面得目录:


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


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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/126845
推荐阅读
相关标签
  

闽ICP备14008679号