Skip to content

Instantly share code, notes, and snippets.

@tkoki
Last active August 7, 2023 17:12
Show Gist options
  • Save tkoki/e5a058c141519c84807afcd67945ed46 to your computer and use it in GitHub Desktop.
Save tkoki/e5a058c141519c84807afcd67945ed46 to your computer and use it in GitHub Desktop.
Unity 2019.3 以降でiOSプロジェクトにAPNS関連のCapabilityを追加する
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
// Unity 2019.3 でGetUnityTargetNameがdeprecatedになってるので。
public class MyBuildPostprocessor {
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path) {
string appName = "<YOUR-APP-NAME>";
string targetName = "Unity-iPhone";
const string entitlements = @"
<?xml version=""1.0"" encoding=""UTF-8\""?>
<!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd"">
<plist version=""1.0"">
<dict>
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>";
if (buildTarget != BuildTarget.iOS) {
return;
}
try {
PBXProject proj = new PBXProject();
string projPath = PBXProject.GetPBXProjectPath(path);
string entitlementFileName = appName + ".entitlements";
string entitlementPath = path + "/" + targetName + "/" + entitlementFileName;
// 1. PBXProject初期化
proj.ReadFromFile(projPath);
string target = proj.GetUnityMainTargetGuid();
// 2. entitlementsファイルを作成する
File.WriteAllText(entitlementPath, entitlements);
proj.AddFile(targetName + "/" + entitlementFileName, entitlementFileName);
proj.AddBuildProperty(target, "CODE_SIGN_ENTITLEMENTS", targetName + "/" + entitlementFileName);
// 3. Linked Frameworks and LibrariesにUserNotifiations.frameworkを追加
proj.AddFrameworkToProject(target, "UserNotifications.framework", false);
// 4. CapabilitiesにBackground Modes -> Remote notificaionsを追加
ProjectCapabilityManager capManager = new ProjectCapabilityManager(projPath, targetName + "/" + entitlementFileName, targetName);
proj.AddCapability(target, PBXCapabilityType.BackgroundModes);
capManager.AddBackgroundModes(BackgroundModesOptions.RemoteNotifications);
// 5. 書き出し
capManager.WriteToFile();
proj.WriteToFile(projPath);
} catch (Exception e) {
Debug.Log($"PostProcessBuild Error {e}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment