スマゲ

スマートなゲームづくりを目指して日々精進

UnityでiOSのローカル通知を実装する

Unity5でiOSのローカル通知を利用する方法まとめてみます

■環境
Mac OS X 10.11.5
Unity 5.4.0f3
Xcode 7.3.1

■通知の許可を求める
iOS8からはアプリがユーザーに対して通知の許可を求める必要があるため、ユーザーに確認用画面を表示する

using UnityEngine;
using System.Collections;
using NotificationServices = UnityEngine.iOS.NotificationServices;
using NotificationType = UnityEngine.iOS.NotificationType;

public class Samples : MonoBehaviour {

    void Start(){
        NotificationServices.RegisterForNotifications(
            NotificationType.Alert | 
            NotificationType.Badge | 
            NotificationType.Sound);
    }
}

■通知を登録する
ユーザーがアプリを最後にプレイしてから3日間プレイしないと通知を出すサンプル

using UnityEngine;
using System.Collections;
using NotificationType = UnityEngine.iOS.NotificationType;
using LocalNotification = UnityEngine.iOS.LocalNotification;
using NotificationServices = UnityEngine.iOS.NotificationServices;

public class Samples : MonoBehaviour {

    public void SetNotification(string message, int delayTime, int badgeNumber = 1){
        var l = new LocalNotification();
        l.applicationIconBadgeNumber = badgeNumber;
        l.fireDate = System.DateTime.Now.AddSeconds(delayTime);
        l.alertBody = message;
        NotificationServices.ScheduleLocalNotification(l);
    }

    void OnApplicationPause(bool isPause){
        if(isPause){
            // 3日間遊ばれていなかったら通知を出す
            SetNotification("Play the game!!", 60 * 60 * 24 * 3);
        } else {
            // 起動時、復帰時に登録してある通知を削除する
            NotificationServices.CancelAllLocalNotifications();
        }
    }
}

■iOSローカル通知サンプルコード
iOSのローカル通知の実装に使えそうな実装を以下にまとめました。Utilっぽく機能毎に切り分けているので、他のプロジェクトにもすぐ入れられると思います。
内容
・通知許可画面の表示
・通知が許可されているかの確認
・通知の登録
・通知のキャンセル
・iOSの設定ページを開く
・アプリアイコンに表示される通知バッヂの削除
github.com

■注意点
Unityはプラグインを書かなくてもiOSのローカル通知を実装することができるが、機能的に足りない部分があるので、それを補う必要がある。
また機能を使うにあたってLocalNotificationなど名前空間がかぶることがあるので実装には気をつける。

■参考
ローカル通知を使う - テラシュールブログ
[Swift] iOS でプッシュ通知の有効・無効を判定する

■関連
Unityで通知アイコンのバッジを削除する(iOS) - スマゲ
【iOS】Unityで通知許可のダイアログを出す - スマゲ