Enable capabilities for Unity3D xCode Project in postprocess

Sam Stone picture Sam Stone · Jun 1, 2017 · Viewed 8.5k times · Source

I have a Unity3D iOS project, where I use Game Center and In-App Purchases(via third-party plugins), but when I build Unity3D project into xCode, in the Capabilities section Game Center and In-App Purchases are disabled. I need to enable them in a PostProcessBuild method. I tried using xCodeApi via this code:

   string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
   PBXProject proj = new PBXProject();

   proj.ReadFromString(File.ReadAllText(projPath));
   string target = proj.TargetGuidByName("Unity-iPhone");

   proj.AddCapability (target, PBXCapabilityType.GameCenter);
   proj.AddCapability (target, PBXCapabilityType.InAppPurchase);

   File.WriteAllText(projPath, proj.ToString());

But after this xCode is unable to open the created project(it just crashes immidietly). How do I add these two capabilities without setting them manually in xCode?

Answer

Iggy picture Iggy · Apr 6, 2020

Here's a new way that this is achievable:

using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.iOS.Xcode;

public class CapabilityPostprocessBuild : IPostprocessBuildWithReport
{
    public int callbackOrder => 999;

    public void OnPostprocessBuild(BuildReport report)
    {
        OnPostprocessBuild(report.summary.platform, report.summary.outputPath);
    }

    public void OnPostprocessBuild(BuildTarget buildTarget, string path)
    {
        if (buildTarget == BuildTarget.iOS)
        {
            string projPath = PBXProject.GetPBXProjectPath(path);

            PBXProject proj = new PBXProject();
            proj.ReadFromFile(projPath);

            ProjectCapabilityManager manager = new ProjectCapabilityManager(
                projPath,
                "Entitlements.entitlements",
                targetGuid: proj.GetUnityMainTargetGuid()
            );

            manager.AddiCloud(true, false, null);

            manager.WriteToFile();
        }
    }
}