Unityの通知機能をiOS/Androidで共通化する方法(Mobile Notifications 2.4.0対応)

Unity

Unityでスマホアプリを開発していると、通知(ローカル通知)の実装は避けて通れません。

本記事では、Unity公式パッケージ「Mobile Notifications(v2.4.0)」を用いて、AndroidとiOSで共通コードベースで通知を扱う方法をまとめます。

また、iOSでのカスタムサウンド設定の落とし穴や、PostProcessBuildを使った設定自動化についても解説します。


使用パッケージ

  • com.unity.mobile.notifications@2.4.0
  • Unity 2022.3 LTS 環境で検証

Androidでの通知設定(概要)

Androidでは通知チャンネルの設定が必要です。

var channel = new AndroidNotificationChannel()
{
    Id = "default_channel",
    Name = "Default Channel",
    Importance = Importance.Default,
    Description = "Generic notifications",
};
AndroidNotificationCenter.RegisterNotificationChannel(channel);

通知の送信は以下のように行います。

var notification = new AndroidNotification();
notification.Title = "お知らせ";
notification.Text = "〇〇の時間です";
notification.FireTime = DateTime.Now.AddSeconds(10);
notification.SmallIcon = "icon_01";
AndroidNotificationCenter.SendNotification(notification, "default_channel");

カスタムサウンドを再生したい場合、res/rawに音声ファイル(.mp3.ogg)を配置し、 notification.Sound = "customsound"; と指定すればOKです。


iOSでの通知設定(概要)

iOSはサウンドやカテゴリの設定にやや制約があります。 カスタムサウンド再生には.caf形式が必要で、バンドル内に含める必要ありです。

var notification = new iOSNotification();
notification.Identifier = "notify_01";
notification.Title = "お知らせ";
notification.Body = "〇〇の時間です";
notification.ShowInForeground = true;
notification.Sound = new iOSNotificationSound() { Name = "customsound.caf" };
iOSNotificationCenter.ScheduleNotification(notification);

.cafファイルを Assets/Plugins/iOS に配置し、Build時に正しくバンドルされるように注意します。


PostProcessBuildで自動化する(iOS)

通知関連設定を自動化するため、PostProcessBuildを使ってInfo.plistXcodeプロジェクトに必要な設定を追加することができます。

[PostProcessBuild]
public static void OnPostProcess(BuildTarget target, string pathToBuiltProject)
{
    if (target == BuildTarget.iOS)
    {
        var plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
        var plist = new PlistDocument();
        plist.ReadFromFile(plistPath);

        var rootDict = plist.root;
        rootDict.SetBoolean("UIBackgroundModes", true); // 必要に応じて設定

        File.WriteAllText(plistPath, plist.WriteToString());
    }
}

両OSで共通化する実装方針

#if UNITY_ANDROID
    // Android用の通知処理
#elif UNITY_IOS
    // iOS用の通知処理
#else
    // エディタ or 他プラットフォーム
#endif

このように、プラットフォーム別に処理を切り分けたうえで、同じ通知トリガー関数から呼び出すように設計すると保守性が高まります。


まとめ

  • Unity公式のMobile NotificationsパッケージはiOS/Android両対応
  • サウンドや通知チャンネルはOS依存が大きいため、事前に仕様を把握して設計すべき
  • PostProcessBuildを活用すると、設定忘れや手動対応を防げる

公開中のアプリ一覧はこちら!

実際にUnityで開発してリリース済みのアプリ一覧をまとめています。

https://syunpp.com/公開中のアプリ一覧/

コメント

タイトルとURLをコピーしました