PackPlatformiOSBuild.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEditor;
  6. #if UNITY_IOS
  7. using UnityEditor.iOS.Xcode;
  8. #endif
  9. namespace Pack
  10. {
  11. public partial class PackPlatformiOS
  12. {
  13. protected override string GetBuildOutputPath()
  14. {
  15. // iOS 的XCode项目路径最好不能有中文,否则易出错
  16. string path = Application.dataPath + PackConstant.BuildAppPath + "/" + GetBuildTarget() + "/" + channelUniqueId;
  17. path = Path.GetFullPath(path).Replace('\\', '/');
  18. return path + "/XCodeProj";
  19. }
  20. public override void BuildClear()
  21. {
  22. base.BuildClear();
  23. DeleteDirectoryAssets(Path.GetFullPath(Application.dataPath + PackConstant.PluginiOSDestPath), true);
  24. DeleteDirectoryAssets(Path.GetFullPath(Application.dataPath + PackConstant.SDKBridgeDestPath), true);
  25. }
  26. protected override void ChangePlayerSettings()
  27. {
  28. base.ChangePlayerSettings();
  29. PlayerSettings.bundleVersion = gameVersionCode.ToString(true);
  30. PlayerSettings.iOS.buildNumber = gameVersionCode;
  31. }
  32. protected override void ChangePlatformSpecial()
  33. {
  34. base.ChangePlatformSpecial();
  35. EditorUtility.DisplayProgressBar("平台特殊设置", "开始平台特殊设置", 0);
  36. if (plugins != null && plugins.Count > 0)
  37. {
  38. CopyUnityAssets(Application.dataPath + PackConstant.PluginiOSSrcPath
  39. , plugins
  40. , Application.dataPath + PackConstant.PluginiOSDestPath
  41. , Application.dataPath + PackConstant.PluginiOSSrcMetaPath
  42. , Application.dataPath + PackConstant.PluginiOSDestMetaPath);
  43. }
  44. EditorUtility.DisplayProgressBar("平台特殊设置", "平台特殊设置", 0.5f);
  45. if (sdkBridges != null && sdkBridges.Count > 0)
  46. {
  47. CopyUnityAssets(Application.dataPath + PackConstant.SDKBridgeSrcPath
  48. , sdkBridges
  49. , Application.dataPath + PackConstant.SDKBridgeDestPath
  50. , Application.dataPath + PackConstant.SDKBridgeSrcMetaPath
  51. , Application.dataPath + PackConstant.SDKBridgeDestMetaPath);
  52. }
  53. EditorUtility.DisplayProgressBar("平台特殊设置", "完成平台特殊设置", 1);
  54. }
  55. protected override BuildOptions ChangeBuildOptionsBefore(BuildOptions buildOptions)
  56. {
  57. buildOptions = base.ChangeBuildOptionsBefore(buildOptions);
  58. return buildOptions;
  59. }
  60. private void CopymmFile(string[] fs,string topath)
  61. {
  62. string path = Application.dataPath + PackConstant.BuildSharedResourcePath + "/Plugins/Special/iOS/";
  63. string outPath = GetBuildOutputPath();
  64. foreach (var item in fs)
  65. {
  66. File.Copy(path + item, Path.Combine(outPath,topath+ "/"+item), true);
  67. }
  68. }
  69. protected override void BuildAppCompleted(BuildOptions buildOptions)
  70. {
  71. base.BuildAppCompleted(buildOptions);
  72. string outPath = GetBuildOutputPath();
  73. // iOS 的XCode项目路径最好不能有中文,否则易出错
  74. // 所以设置一个txt文件来标注项目名字
  75. string dirPath = Path.GetDirectoryName(outPath);
  76. if (!Directory.Exists(dirPath))
  77. {
  78. Directory.CreateDirectory(dirPath);
  79. }
  80. string[] files = Directory.GetFiles(dirPath, ".txt");
  81. bool exist = false;
  82. string packFileName = GetPackFileName();
  83. foreach (string file in files)
  84. {
  85. if (Path.GetFileNameWithoutExtension(file) == packFileName)
  86. {
  87. exist = true;
  88. }
  89. else
  90. {
  91. File.Delete(file);
  92. }
  93. }
  94. if (!exist)
  95. {
  96. //packFileName = packFileName.Replace(" ", "_");
  97. packFileName = packFileName.Replace(":", "_");
  98. File.Create(Path.Combine(dirPath, packFileName + ".txt"));
  99. }
  100. // 为了过审核,需要删除OpenUrl
  101. //File.Copy(Application.dataPath + PackConstant.BuildSharedResourcePath + "/Plugins/Special/iOS/libiPhone-lib.a", Path.Combine(outPath, "Libraries/libiPhone-lib.a"), true);
  102. //CopymmFile(new string[] { "LuLuConnector.h", "LuLuConnector.mm" }, "Classes");
  103. ChangeXCodeProject(buildOptions);
  104. }
  105. #if UNITY_IOS
  106. private void AddFrameworkToProject(PBXProject pro, string target, string[] libs, bool weak)
  107. {
  108. foreach (var item in libs)
  109. {
  110. pro.AddFrameworkToProject(target,item,weak);
  111. }
  112. }
  113. private PlistElementArray PlistAddUrlType(PlistDocument plist, PlistElementArray urlTypes,string name,string role, string url)
  114. {
  115. if (urlTypes == null)
  116. {
  117. if (plist.root.values.ContainsKey("CFBundleURLTypes"))
  118. {
  119. urlTypes = plist.root["CFBundleURLTypes"].AsArray();
  120. }
  121. else
  122. urlTypes = plist.root.CreateArray("CFBundleURLTypes");
  123. }
  124. PlistElementDict dict = urlTypes.AddDict();
  125. dict.SetString("CFBundleTypeRole", role);
  126. dict.SetString("CFBundleURLName", name);
  127. dict.CreateArray("CFBundleURLSchemes").AddString(url);
  128. return urlTypes;
  129. }
  130. private void PlistCreateArray(PlistDocument plist, string name,string[] values)
  131. {
  132. PlistElementArray arr = plist.root.CreateArray(name);
  133. foreach (var item in values)
  134. {
  135. arr.AddString(item);
  136. }
  137. }
  138. class DictItem
  139. {
  140. public string type;
  141. public object data;
  142. public DictItem(string type,object data)
  143. {
  144. this.data = data;
  145. this.type = type;
  146. }
  147. }
  148. private PlistElementDict PlistCreateDict(PlistDocument plist,string name, Dictionary<string, DictItem> keyValues,bool isRoot = false, PlistElementDict root = null)
  149. {
  150. PlistElementDict dict = plist.root;
  151. if (root == null)
  152. {
  153. root = plist.root;
  154. }
  155. if (!isRoot)
  156. dict = root.CreateDict(name);
  157. foreach (var item in keyValues)
  158. {
  159. switch (item.Value.type)
  160. {
  161. case "bool":
  162. {
  163. dict.SetBoolean(item.Key,(bool)item.Value.data);
  164. }
  165. break;
  166. case "int":
  167. {
  168. dict.SetInteger(item.Key,(int)item.Value.data);
  169. }
  170. break;
  171. case "float":
  172. {
  173. dict.SetReal(item.Key,(float)item.Value.data);
  174. }
  175. break;
  176. case "date":
  177. {
  178. dict.SetDate(item.Key,(System.DateTime)item.Value.data);
  179. }
  180. break;
  181. case "string":
  182. {
  183. dict.SetString(item.Key,(string)item.Value.data);
  184. }
  185. break;
  186. }
  187. }
  188. return dict;
  189. }
  190. #endif
  191. protected void ChangeXCodeProject(BuildOptions buildOptions)
  192. {
  193. #if UNITY_IOS
  194. EditorUtility.DisplayProgressBar("修改XCodeProject", "开始修改XCodeProject", 0);
  195. string outPath = GetBuildOutputPath();
  196. PBXProject pbxProject = new PBXProject();
  197. string pbxprojPath = PBXProject.GetPBXProjectPath(outPath);
  198. pbxProject.ReadFromFile(pbxprojPath);
  199. string targetGuid = pbxProject.GetUnityMainTargetGuid();//pbxProject.TargetGuidByName("Unity-iPhone");
  200. string unityFmwkGUid = pbxProject.GetUnityFrameworkTargetGuid();
  201. Debug.Log($"=================== targetGuid = {targetGuid} ===============");
  202. pbxProject.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO");//enable Bitcode 设置 为 no
  203. pbxProject.AddBuildProperty(targetGuid, "OTHER_LDFLAGS", "-all_load -ObjC -lc++");
  204. pbxProject.AddBuildProperty(unityFmwkGUid, "OTHER_LDFLAGS", " -all_load -ObjC -lc++");
  205. // 设置 Allow Non-modular Includes in Framework Modules 为 true
  206. pbxProject.SetBuildProperty(targetGuid, "CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES", "YES");
  207. pbxProject.SetBuildProperty(unityFmwkGUid, "CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES", "YES");
  208. pbxProject.AddCapability(targetGuid,PBXCapabilityType.InAppPurchase);//内购
  209. pbxProject.AddCapability(targetGuid,PBXCapabilityType.SignInWithApple);//苹果登录
  210. //AddFrameworkToProject(pbxProject, unityFmwkGUid, new string[] { "Accelerate.framework" },false);
  211. //pbxProject.AddAssetTagToDefaultInstall
  212. pbxProject.WriteToFile(pbxprojPath);
  213. EditorUtility.DisplayProgressBar("修改XCodeProject", "修改project.pbxproj完成", 0.25f);
  214. string plistPath = Path.Combine(outPath, "Info.plist");
  215. PlistDocument plistDocument = new PlistDocument();
  216. plistDocument.ReadFromFile(plistPath);
  217. PlistCreateArray(plistDocument, "LSApplicationQueriesSchemes", new string[] { "fbauth2", "fbapi", "fb-messenger-share-api", "fbshareextension", "fb-messenger-api"});
  218. PlistCreateArray(plistDocument, "UIAppFonts", new string[] {
  219. "Inter-Black.ttf",
  220. "Inter-Bold.ttf",
  221. "Inter-ExtraBold.ttf",
  222. "Inter-Light.ttf",
  223. "Inter-Medium.ttf",
  224. "Inter-Regular.ttf",
  225. "Inter-SemiBold.ttf",
  226. "Inter-Thin.ttf",
  227. });
  228. //PlistCreateArray(plistDocument, "Queried URL Schemes", new string[] { "vk", "vk-share", "vkauthorize" });
  229. PlistCreateDict(plistDocument, "NSAppTransportSecurity", new Dictionary<string, DictItem>() { { "NSAllowsArbitraryLoads", new DictItem("bool",true)} });
  230. //Facebook AppID IOS: 1734387583815032
  231. PlistCreateDict(plistDocument,"",new Dictionary<string, DictItem>()
  232. {
  233. { "xuanyou_GameId", new DictItem("string", "127") },
  234. { "FacebookAppID", new DictItem("string", "849135470863608") },
  235. { "FacebookDisplayName", new DictItem("string", "The King of Poring: Origin") },
  236. { "NSUserTrackingUsageDescription", new DictItem("string", "App would like to access IDFA for tracking purpose") },
  237. //{ "NSPhotoLibraryAddUsageDescription", new DictItem("string", "Photo Library Add Usage Description") },
  238. //{ "NSPhotoLibraryUsageDescription", new DictItem("string", "Photo Library Usage Description") },
  239. },true);
  240. PlistElementDict dict = PlistCreateDict(plistDocument, "SPAdjustConfig", new Dictionary<string, DictItem>()
  241. {
  242. { "appToken", new DictItem("string","zg6ixp19pdz4")},
  243. });
  244. PlistCreateDict(plistDocument, "eventTokens", new Dictionary<string, DictItem>()
  245. {
  246. { "activeEventToken", new DictItem("string","kky0yu")},
  247. { "createRoleToken", new DictItem("string","1p4znl")},
  248. { "firstPayEventToken", new DictItem("string","p6p840")},
  249. { "noviceGuideEventToken", new DictItem("string","21l1no")},
  250. { "payEventToken", new DictItem("string","ot7zkz")},
  251. { "registerEventToken", new DictItem("string","6s22py")},
  252. },false, dict);
  253. PlistElementArray arr = PlistAddUrlType(plistDocument, null, "facebook", "Editor", "fb849135470863608");
  254. PlistAddUrlType(plistDocument, arr, "com.boliking.ios", "Editor", "com.boliking.ios");
  255. PlistAddUrlType(plistDocument, arr, "com.boliking.ios", "Editor", "827002282646-eefr6v53fvhmfts5d5huo9ptir8ola1k.apps.googleusercontent.com");
  256. plistDocument.WriteToFile(plistPath);
  257. EditorUtility.DisplayProgressBar("修改XCodeProject", "修改info.list完成", 0.5f);
  258. if ((buildOptions & BuildOptions.AcceptExternalModificationsToPlayer) == 0)
  259. {
  260. string deviceSettingsMMPath = Path.Combine(outPath, "Classes/Unity/DeviceSettings.mm");
  261. ObjCScript script = new ObjCScript(deviceSettingsMMPath);
  262. script.AddImport("WentingSDK.h");
  263. script.ReplaceInLine("_VendorID = AllocCString([[UIDevice currentDevice].identifierForVendor UUIDString]);",
  264. "_VendorID = AllocCString([WentingSDK GetUUID]);");
  265. script.Save();
  266. /*
  267. string unityAppControllerMMPath = Path.Combine(outPath, "Classes/UnityAppController.mm");
  268. script = new ObjCScript(unityAppControllerMMPath);
  269. //script.AddImport("OEGFramework", true, true);
  270. int idx = script.FindLine("::printf(\"-> applicationDidFinishLaunching()\\n\");");
  271. script.InsertLine(idx, idx + 1);
  272. script.InsertLine(idx, idx + 2, "[OEGManager handleDidFinishLaunchingWithOptions:launchOptions];");
  273. script.InsertLine(idx, idx + 3, "// If you want to control Firebase push message you can add below code");
  274. script.InsertLine(idx, idx + 4, "[[FirebaseService sharedManager] messagingDelegate:self];");
  275. script.InsertLine(idx, idx + 5);
  276. idx = script.FindLine("::printf(\"-> applicationWillResignActive()\\n\");");
  277. script.InsertLine(idx, idx + 1);
  278. script.InsertLine(idx, idx + 2, "[OEGManager handleWillResignActive];");
  279. script.InsertLine(idx, idx + 3);
  280. idx = script.FindLine("::printf(\"-> applicationDidEnterBackground()\\n\");");
  281. script.InsertLine(idx, idx + 1);
  282. script.InsertLine(idx, idx + 2, " [OEGManager handleDidEnterBackground];");
  283. script.InsertLine(idx, idx + 3);
  284. idx = script.FindLine("::printf(\"-> applicationWillEnterForeground()\\n\");");
  285. script.InsertLine(idx, idx + 1);
  286. script.InsertLine(idx, idx + 2, "[OEGManager handleWillEnterForeground];");
  287. script.InsertLine(idx, idx + 3);
  288. idx = script.FindLine("::printf(\"-> applicationDidBecomeActive()\\n\");");
  289. script.InsertLine(idx, idx + 1);
  290. script.InsertLine(idx, idx + 2, "[OEGManager handleDidBecomeActive];");
  291. script.InsertLine(idx, idx + 3);
  292. idx = script.FindLine("::printf(\"-> applicationWillTerminate()\\n\");");
  293. script.InsertLine(idx, idx + 1);
  294. script.InsertLine(idx, idx + 2, "[OEGManager handleWillTerminate];");
  295. script.InsertLine(idx, idx + 3);
  296. idx = script.FindLine("@end") - 1;
  297. //script.InsertLine(idx, idx + 1);
  298. //script.InsertLine(idx, idx + 2, "- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {");
  299. //script.InsertLine(idx, idx + 3, " [OEGManager handleDidRegisterForRemoteNotificationsWithDeviceToken:deviceToken];\n}");
  300. script.InsertLine(idx, idx + 1);
  301. script.InsertLine(idx, idx + 2, "- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {");
  302. script.InsertLine(idx, idx + 3, " return [OEGManager handleOpenURL:url options:options];\n}");
  303. script.InsertLine(idx, idx + 4);
  304. script.InsertLine(idx, idx + 5);
  305. //
  306. idx = script.FindLine("- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken") + 1;
  307. script.InsertLine(idx, idx + 1);
  308. script.InsertLine(idx, idx + 2, "[OEGManager handleDidRegisterForRemoteNotificationsWithDeviceToken:deviceToken];");
  309. script.InsertLine(idx, idx + 3);
  310. script.Save();
  311. */
  312. }
  313. EditorUtility.DisplayProgressBar("修改XCodeProject", "完成修改XCodeProject", 1);
  314. EditorUtility.ClearProgressBar();
  315. #endif
  316. }
  317. protected class ObjCScript
  318. {
  319. private string m_FilePath;
  320. private List<string> m_Lines;
  321. private int importIdx = -1;
  322. private int includeIdx = -1;
  323. public ObjCScript(string filePath)
  324. {
  325. m_FilePath = filePath;
  326. if (!File.Exists(filePath))
  327. {
  328. PackLog.LogError(filePath + " is not Exist");
  329. return;
  330. }
  331. m_Lines = new List<string>(File.ReadAllLines(filePath));
  332. for (int i = 0, iMax = m_Lines.Count; i < iMax; i++)
  333. {
  334. string line = m_Lines[i].Trim();
  335. if (line.StartsWith("#import "))
  336. {
  337. importIdx = i;
  338. }
  339. if (line.StartsWith("#include "))
  340. {
  341. includeIdx = i;
  342. }
  343. }
  344. }
  345. public void AddImport(string name, bool isframework = false,bool ismode = false)
  346. {
  347. if (m_Lines == null)
  348. {
  349. PackLog.LogError(m_FilePath + " is not Valid Objc Script");
  350. return;
  351. }
  352. int idx = -1;
  353. if (importIdx >= 0 && importIdx < m_Lines.Count)
  354. {
  355. idx = importIdx;
  356. }
  357. if (idx == -1)
  358. {
  359. if (includeIdx >= 0 && includeIdx < m_Lines.Count)
  360. {
  361. idx = includeIdx;
  362. }
  363. }
  364. if (idx == -1)
  365. {
  366. PackLog.LogError(m_FilePath + " is not Valid Objc Script");
  367. return;
  368. }
  369. if (isframework)
  370. {
  371. idx = idx + 1;
  372. if (ismode)
  373. {
  374. m_Lines.Insert(idx, "@import " + name + ";");
  375. }
  376. else
  377. {
  378. m_Lines.Insert(idx, "#import <" + name + ">");
  379. }
  380. }
  381. else
  382. {
  383. idx = idx + 1;
  384. m_Lines.Insert(idx, "#import \"" + name + "\"");
  385. }
  386. }
  387. public int FindLine(string str)
  388. {
  389. if (m_Lines == null)
  390. {
  391. PackLog.LogError(m_FilePath + " is not Valid Objc Script");
  392. return -1;
  393. }
  394. return m_Lines.FindIndex((x) => x.Contains(str));
  395. }
  396. public void InsertLine(int alginIdx, int insertIdx, string str = "")
  397. {
  398. if (m_Lines == null)
  399. {
  400. PackLog.LogError(m_FilePath + " is not Valid Objc Script");
  401. return;
  402. }
  403. if (alginIdx < 0 || alginIdx >= m_Lines.Count)
  404. {
  405. PackLog.LogError(" alginIdx is not Valid Value " + alginIdx);
  406. return;
  407. }
  408. if (insertIdx < 0 || insertIdx >= m_Lines.Count)
  409. {
  410. PackLog.LogError(" insertIdx is not Valid Value " + insertIdx);
  411. return;
  412. }
  413. if (string.IsNullOrEmpty(str))
  414. {
  415. m_Lines.Insert(insertIdx, "");
  416. return;
  417. }
  418. string line = m_Lines[alginIdx];
  419. int len1 = line.Length;
  420. int len2 = len1 - line.TrimStart().Length;
  421. string startStr = line.Substring(0, len2);
  422. m_Lines.Insert(insertIdx, startStr + str);
  423. return;
  424. }
  425. public void ReplaceInLine(string oldStr, string newStr)
  426. {
  427. if (m_Lines == null)
  428. {
  429. PackLog.LogError(m_FilePath + " is not Valid Objc Script");
  430. return;
  431. }
  432. for (int i = 0, iMax = m_Lines.Count; i < iMax; i++)
  433. {
  434. string line = m_Lines[i];
  435. if (line.Contains(oldStr))
  436. {
  437. m_Lines[i] = line.Replace(oldStr, newStr);
  438. }
  439. }
  440. }
  441. public void Save()
  442. {
  443. if (m_Lines == null) return;
  444. File.WriteAllLines(m_FilePath, m_Lines);
  445. }
  446. public override string ToString()
  447. {
  448. System.Text.StringBuilder sb = new System.Text.StringBuilder();
  449. for (int i = 0, iMax = m_Lines.Count; i < iMax; i++)
  450. {
  451. sb.AppendLine(m_Lines[i]);
  452. }
  453. return sb.ToString();
  454. }
  455. }
  456. }
  457. }