在 Unity3d 導出 iOS 項目後,常常需要定製一些選項,例如指定額外的 framework,修改 Info.plist 等。
Unity3d 在導出工程的時候提供兩個選項:替換整個項目「replace」和追加變動「append」。一旦使用了 replace 選項,之前所有手工設置的變更都會丟失,需要重新設置。
那麼有沒有一種方法可以在導出項目的時候對 Xcode 項目進行自動化配置呢?正好 Unity3d 官方提供了一個叫 xcodeapi 的項目,提供了一套簡單易用的接口滿足一些常見的定製需求。
從 bitbucket 上下載 xcodeapi 的源碼,放到 Unity 項目的 Assets 目錄下任意位置,例如 /path/to/project/Assets/Editor/xcodeapi 然後創建一個 MonoBehaviour 的子類,並在其中實現帶有 [PostProcessBuild] 屬性的 public static void OnPostprocessBuild (BuildTarget BuildTarget, string path); 方法:
如果有多個 PostProcessBuild 屬性,可以使用 [PostProcessBuildAttribute(1)] 來指明運行的順序,詳情見此文檔。
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using System.Collections;
using System.IO;
public class XCodeProjectMod : MonoBehaviour {
[PostProcessBuild]
public static void OnPostprocessBuild (BuildTarget BuildTarget, string path) {
if (BuildTarget == BuildTarget.iPhone) {
// 添加額外的 AssetsLibrary.framework
// 用於檢測相冊權限等功能
string projPath = PBXProject.GetPBXProjectPath (path);
PBXProject proj = new PBXProject ();
proj.ReadFromString (File.ReadAllText (projPath));
string target = proj.TargetGuidByName ("Unity-iPhone");
// add extra framework(s)
proj.AddFrameworkToProject (target, "AssetsLibrary.framework", false);
// set code sign identity & provisioning profile
proj.SetBuildProperty (target, "CODE_SIGN_IDENTITY", "iPhone Distribution: _______________");
proj.SetBuildProperty (target, "PROVISIONING_PROFILE", "********-****-****-****-************");
// rewrite to file
File.WriteAllText (projPath, proj.WriteToString ());
// 由於我的開發機是英文系統,但遊戲需要設置爲中文;
// 需要在修改 Info.plist 中的 CFBundleDevelopmentRegion 字段爲 zh_CN
// Get plist
string plistPath = path + "/Info.plist";
PlistDocument plist = new PlistDocument();
plist.ReadFromString(File.ReadAllText(plistPath));
// Get root
PlistElementDict rootDict = plist.root;
// Change value of CFBundleDevelopmentRegion in Xcode plist
rootDict.SetString("CFBundleDevelopmentRegion", "zh_CN");
PlistElementArray urlTypes = rootDict.CreateArray("CFBundleURLTypes");
// add weixin url scheme
PlistElementDict wxUrl = urlTypes.AddDict();
wxUrl.SetString("CFBundleTypeRole", "Editor");
wxUrl.SetString("CFBundleURLName", "weixin");
PlistElementArray wxUrlScheme = wxUrl.CreateArray("CFBundleURLSchemes");
wxUrlScheme.AddString("____________");
// Write to file
File.WriteAllText(plistPath, plist.WriteToString());
}
}
}