This commit is contained in:
qiuqiu 2025-04-04 11:47:20 +08:00
parent 469d028d7b
commit 135fa402ff
3 changed files with 336 additions and 62 deletions

16
.idea/workspace.xml generated
View File

@ -7,9 +7,8 @@
</component>
<component name="ChangeListManager">
<list default="true" id="fec10672-acda-4616-894b-a4b6f93aea6f" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/笔记文件/日记/2025_04_03_星期四.md" beforeDir="false" afterPath="$PROJECT_DIR$/笔记文件/日记/2025_04_03_星期四.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/笔记文件/日记/2025_04_04_星期五.md" beforeDir="false" afterPath="$PROJECT_DIR$/笔记文件/日记/2025_04_04_星期五.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/笔记文件/2.笔记/xcode依赖处理 打包后处理通过podfile添加第三方库.md" beforeDir="false" afterPath="$PROJECT_DIR$/笔记文件/2.笔记/xcode依赖处理 打包后处理通过podfile添加第三方库.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/笔记文件/2.笔记/安卓依赖库 导入 后处理.md" beforeDir="false" afterPath="$PROJECT_DIR$/笔记文件/2.笔记/安卓依赖库 导入 后处理.md" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -54,7 +53,7 @@
<workItem from="1743054128839" duration="1104000" />
<workItem from="1743470619023" duration="313000" />
<workItem from="1743486676893" duration="3523000" />
<workItem from="1743645292579" duration="4953000" />
<workItem from="1743645292579" duration="5250000" />
</task>
<task id="LOCAL-00001" summary="测试提交">
<created>1742956649478</created>
@ -147,7 +146,14 @@
<option name="project" value="LOCAL" />
<updated>1743677121508</updated>
</task>
<option name="localTasksCounter" value="14" />
<task id="LOCAL-00014" summary="提交">
<created>1743738149122</created>
<option name="number" value="00014" />
<option name="presentableId" value="LOCAL-00014" />
<option name="project" value="LOCAL" />
<updated>1743738149122</updated>
</task>
<option name="localTasksCounter" value="15" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">

View File

@ -1,23 +1,101 @@
#unity/代码缓存
## PostProcessBuildClass
有一个前提macos已经正确安装了pod相关的工具
## PostProcessBuildClass
``` cs
#if UNITY_IOS
using System.Diagnostics;
using System.IO;
using System.Threading;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
using UnityEditor.iOS.Xcode;
using Debug = UnityEngine.Debug;
/// <summary>
/// xcode打包后处理
/// </summary>
static class PostProcessBuildClass
{
using System.Diagnostics;
using System.Threading;
using Debug = UnityEngine.Debug;
using System;
static class PostProcessBuildClass {
[PostProcessBuild]
public static void ChangeXcodePlist(BuildTarget pBuildTarget, string pPath) {
// Debug.LogError("Post process build ChangeXcodePlist");
if (pBuildTarget == BuildTarget.iOS) {
#region 添加 ATT广告跟踪权限
AddInfoByTracking(pPath);
#endregion
#region 添加Meta 广告变现平台 SKAdNetwork相关
AddSKAdNetworkItems(pPath);
#endregion
}
}
/// <summary>
/// 添加广告追踪权限
/// </summary>
/// <param name="path"></param>
private static void AddInfoByTracking(string path)
{
string plistPath = Path.Combine(path, "Info.plist");
PlistDocument plist = new PlistDocument();
plist.ReadFromFile(plistPath);
PlistElementDict rootDict = plist.root;
rootDict.SetString("NSUserTrackingUsageDescription", "We need your consent to track advertisements to provide better services。");
File.WriteAllText(plistPath, plist.WriteToString());
}
/// <summary>
/// 添加Meta 广告变现平台 SKAdNetwork相关
/// </summary>
/// <param name="path"></param>
private static void AddSKAdNetworkItems(string path)
{
string plistPath = Path.Combine(path, "Info.plist");
PlistDocument plist = new PlistDocument();
plist.ReadFromFile(plistPath);
PlistElementDict rootDict = plist.root;
// 获取或创建SKAdNetworkItems数组
PlistElementArray skAdNetworkItems;
if (rootDict.values.ContainsKey("SKAdNetworkItems"))
{
skAdNetworkItems = rootDict["SKAdNetworkItems"].AsArray();
}
else
{
skAdNetworkItems = rootDict.CreateArray("SKAdNetworkItems");
}
// 添加SKAdNetworkIdentifier
AddSkAdNetworkIdentifier(skAdNetworkItems, "v9wttpbfk9.skadnetwork");
AddSkAdNetworkIdentifier(skAdNetworkItems, "n38lu8286q.skadnetwork");
// 保存修改
plist.WriteToFile(plistPath);
}
private static void AddSkAdNetworkIdentifier(PlistElementArray array, string identifier)
{
foreach (var element in array.values)
{
if (element.AsDict().values.ContainsKey("SKAdNetworkIdentifier") &&
element.AsDict()["SKAdNetworkIdentifier"].AsString() == identifier)
{
return; // 已存在,不重复添加
}
}
PlistElementDict dict = array.AddDict();
dict.SetString("SKAdNetworkIdentifier", identifier);
}
private static Thread podFileCheckThread;
private const int timeOutSeconds = 10;
@ -26,7 +104,10 @@ static class PostProcessBuildClass
{
if (pBuildTarget == BuildTarget.iOS)
{
AddSDKFramework(pPath);
AddSwiftUsed(pPath);
InitPodFile(pPath);
AddAudienceNetwork(pPath);
AddSurveyMonkey(pPath);
PodInstall(pPath);
}
@ -55,12 +136,16 @@ end";
}
}
/// <summary>
/// 添加调查问卷 相关引用依赖包
/// </summary>
/// <param name="pPath"></param>
private static void AddSurveyMonkey(string pPath)
{
string varPodfilePath = Path.Combine(pPath, "Podfile");
string varPodfileContent = File.ReadAllText(varPodfilePath);
// 检查是否已包含SurveyMonkey
if (!varPodfileContent.Contains("pod 'surveymonkey-ios-sdk', '~> 2.1.2'"))
{
@ -78,60 +163,174 @@ end";
}
/// <summary>
/// 在pod 设置插件库之后. 执行pod install
/// 添加meta广告变现
/// </summary>
/// <param name="pPath"></param>
private static void AddAudienceNetwork(string pPath)
{
string varPodfilePath = Path.Combine(pPath, "Podfile");
string varPodfileContent = File.ReadAllText(varPodfilePath);
// 检查是否已包含SurveyMonkey
if (!varPodfileContent.Contains("pod 'FBAudienceNetwork'"))
{
string varInsertionPoint1 = "target 'UnityFramework' do";
int varIndex1 = varPodfileContent.IndexOf(varInsertionPoint1) + varInsertionPoint1.Length;
string varToInsert1 = "\n pod 'FBAudienceNetwork'";
varPodfileContent = varPodfileContent.Insert(varIndex1, varToInsert1);
File.WriteAllText(varPodfilePath, varPodfileContent);
}
}
/// <summary>
/// 添加广告SDK 相关引用依赖包
/// </summary>
/// <param name="pPath"></param>
private static void AddAdvertisement(string pPath)
{
string varPodfilePath = Path.Combine(pPath, "Podfile");
string varPodfileContent = File.ReadAllText(varPodfilePath);
bool needWrite = false;
// 检查是否已包含广告引用
if (!varPodfileContent.Contains("pod 'TPNiOS'"))
{
string varInsertionPoint1 = "target 'UnityFramework' do";
int varIndex1 = varPodfileContent.IndexOf(varInsertionPoint1) + varInsertionPoint1.Length;
string varToInsert1 = "\n pod 'TPNiOS'";
varPodfileContent = varPodfileContent.Insert(varIndex1, varToInsert1);
needWrite = true;
}
if (!varPodfileContent.Contains("pod 'TPNUnityAdsSDKAdapter'"))
{
string varInsertionPoint1 = "target 'UnityFramework' do";
int varIndex1 = varPodfileContent.IndexOf(varInsertionPoint1) + varInsertionPoint1.Length;
string varToInsert1 = "\n pod 'TPNUnityAdsSDKAdapter'";
varPodfileContent = varPodfileContent.Insert(varIndex1, varToInsert1);
needWrite = true;
}
if (!varPodfileContent.Contains("pod 'TPNAdmobSDKAdapter'"))
{
string varInsertionPoint1 = "target 'UnityFramework' do";
int varIndex1 = varPodfileContent.IndexOf(varInsertionPoint1) + varInsertionPoint1.Length;
string varToInsert1 = "\n pod 'TPNAdmobSDKAdapter'";
varPodfileContent = varPodfileContent.Insert(varIndex1, varToInsert1);
needWrite = true;
}
if (needWrite)
{
File.WriteAllText(varPodfilePath, varPodfileContent);
}
}
private static void AddSDKFramework(string pPath)
{
string projPath = PBXProject.GetPBXProjectPath(pPath);
PBXProject proj = new PBXProject();
proj.ReadFromFile(projPath);
string target = proj.GetUnityMainTargetGuid();
proj.AddFrameworkToProject(target, "StoreKit.framework", false); //添加商店评价相关
proj.WriteToFile(projPath);
}
/// <summary>
/// 添加 总是允许使用Swift编译
/// </summary>
/// <param name="pPath"></param>
private static void AddSwiftUsed(string pPath)
{
// 获取Xcode项目路径
string projPath = PBXProject.GetPBXProjectPath(pPath);
PBXProject proj = new PBXProject();
proj.ReadFromFile(projPath);
// 获取主目标
string targetGuid = proj.GetUnityMainTargetGuid();
// 设置"Always Embed Swift Standard Libraries"为YES
proj.SetBuildProperty(targetGuid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES");
// 保存修改
proj.WriteToFile(projPath);
}
/// <summary>
/// 执行pod install同步方式
/// </summary>
private static void PodInstall(string pPath)
{
Debug.Log(pPath);
string varPodfilePath = Path.Combine(pPath, "Podfile");
void CheckFile()
Debug.Log("=== 开始执行Pod安装流程 ===");
if (!Directory.Exists(pPath))
{
int elapsedSeconds = 0;
while (elapsedSeconds < timeOutSeconds)
{
if (File.Exists(varPodfilePath))
{
// Run pod install or update
string code = $"-c \"cd '{pPath}' && pod install\"";
ProcessStartInfo varProcessStartInfo = new ProcessStartInfo("sh", code)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Process varProcess = new Process();
varProcess.StartInfo = varProcessStartInfo;
varProcess.StartInfo.EnvironmentVariables["LC_ALL"] = "en_US.UTF-8";
varProcess.StartInfo.EnvironmentVariables["LANG"] = "en_US.UTF-8";
varProcess.EnableRaisingEvents = true;
varProcess.Start();
string varOutput = varProcess.StandardOutput.ReadToEnd();
string varErr = varProcess.StandardError.ReadToEnd();
varProcess.WaitForExit();
Debug.Log("======> Pod install output: " + varOutput);
if (!string.IsNullOrEmpty(varErr))
{
Debug.LogError("======> Pod install error: " + varErr);
}
break;
}
Thread.Sleep(1000); // 等待一秒再检查
elapsedSeconds++;
}
Debug.LogError($"Xcode工程路径不存在: {pPath}");
return;
}
podFileCheckThread = new Thread(CheckFile);
podFileCheckThread.Start();
string podfilePath = Path.Combine(pPath, "Podfile");
if (!File.Exists(podfilePath))
{
Debug.LogError($"Podfile文件不存在: {podfilePath}");
return;
}
try
{
// 转义路径中的单引号
string escapedPath = pPath.Replace("'", "'\\''");
string appleScript = $@"
tell application ""Terminal""
activate
do script ""cd '{escapedPath}' && pod install && exit""
end tell";
Debug.Log($"正在启动终端执行pod install...");
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = "/usr/bin/osascript",
Arguments = $"-e '{appleScript}'",
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true
};
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
string error = process.StandardError.ReadToEnd();
Debug.LogError($"启动终端失败: {error}");
}
else
{
Debug.Log("已启动终端执行pod install请稍后在终端中查看结果");
}
}
}
catch (Exception ex)
{
Debug.LogError($"执行命令时发生异常: {ex}");
}
Debug.Log("=== Pod安装流程结束 ===");
}
}
}
#endif
```

View File

@ -1,4 +1,5 @@
#unity/日常积累
#unity/代码缓存
假如只安装了安卓的组件没安装ios的组件直接导入安卓依赖库会报错手动优化方式
@ -8,4 +9,72 @@
代码优化方式参考:
![[img_v3_02ka_c0698d1e-30c7-48e4-bab6-58bc51fe4dhu.jpg]]
![[img_v3_02ka_c0698d1e-30c7-48e4-bab6-58bc51fe4dhu.jpg]]
最终实现,逻辑参考:
## ExternalDependencyManagerResolver
``` cs
using System.Reflection;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
public class ExternalDependencyManagerResolver
{
private static bool hasProcessed = false; //确保只执行一次
private static PluginImporter pluginImporter;
[DidReloadScripts]
private static void OnScriptsReloaded()
{
if (hasProcessed) return;
hasProcessed = true;
string IOSResolverPath = "Assets/A_PLink_Public/Scripts/Tools/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.dll";
string JarResolverPath = "Assets/A_PLink_Public/Scripts/Tools/ExternalDependencyManager/Editor/1.2.182/Google.JarResolver.dll";
if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
{
SetPluginImporter(IOSResolverPath, true);
SetPluginImporter(JarResolverPath, false);
}
else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
{
SetPluginImporter(IOSResolverPath, false);
SetPluginImporter(JarResolverPath, true);
}
else
{
SetPluginImporter(IOSResolverPath, false);
SetPluginImporter(JarResolverPath, false);
}
}
private static void SetPluginImporter(string path,bool isSet)
{
pluginImporter = AssetImporter.GetAtPath(path) as PluginImporter;
if (pluginImporter != null)
{
var type = typeof(PluginImporter);
var property = type.GetProperty("ValidateReferences", BindingFlags.NonPublic | BindingFlags.Instance);
if (property != null)
{
// AssetDatabase.DisallowAutoRefresh();
property.SetValue(pluginImporter, isSet);
// pluginImporter.SaveAndReimport();
// AssetDatabase.AllowAutoRefresh();
Debug.Log($"{path}设置完成");
}
else
{
Debug.LogError("无法找到 ValidateReferences 属性");
}
Debug.Log("插件导入设置已更新");
}
else
{
Debug.LogError("未找到插件Importer");
}
}
}
```