Unityの通知実装まとめ:AndroidとiOSの違いと共通化戦略(Mobile Notifications v2.4.0対応)
Unityでスマホアプリを作っていて、ローカル通知を実装したいと思ったことはありませんか?
私自身、AndroidとiOS両対応のアプリをUnityで開発する中で、通知機能に思った以上にハマったので、この記事では Unity公式パッケージ Mobile Notifications (v2.4.0) を使って、両OS対応の通知を共通コードで管理する方法をまとめます。
使用パッケージ
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"; // res/drawableに配置
AndroidNotificationCenter.SendNotification(notification, "default_channel");
カスタムサウンドについて
res/raw に customsound.ogg を配置
以下のように指定するだけで再生可能です:
notification.Sound = "customsound";
Android側は比較的素直です。
iOS側の実装ポイント
iOSではファイル形式や配置場所に厳しいルールがあります。
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);
注意点
customsound.caf を Assets/Plugins/iOS/ に配置
Xcodeプロジェクトに自動で追加されるように注意
PostProcessBuildを活用して自動化する
毎回Xcodeで手作業するのは非効率。
Unityの PostProcessBuild を使えば、Info.plist の編集などを自動化できます。
[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;
var bgModes = rootDict.CreateArray("UIBackgroundModes");
bgModes.AddString("remote-notification"); // 必要に応じて追加
File.WriteAllText(plistPath, plist.WriteToString());
}
}
両OSで共通化する方法
通知処理はプラットフォームごとに分岐して、トリガーだけ共通関数で管理するのがオススメです。
public void ScheduleLocalNotification()
{
#if UNITY_ANDROID
SendAndroidNotification();
#elif UNITY_IOS
SendIOSNotification();
#endif
}
まとめ
UnityのMobile NotificationsパッケージでiOS/Androidの通知を統一的に管理できる
OSごとの制約(サウンド・チャンネル・ファイル配置)に注意
PostProcessBuildを活用してビルド自動化&手戻り削減がおすすめ
ブログでもUnityや個人開発ネタを発信中です!
開発ノウハウやアプリ制作過程、Unity連携系のハマりポイントなど
より深掘りした内容をブログにまとめています。
▶ https://syunpp.com
公開中のアプリ一覧はこちら!
実際にUnityで開発してリリース済みのアプリ一覧をまとめています。
▶ https://syunpp.com/公開中のアプリ一覧/
Discussion