【Unity】ローカルプッシュ通知(iOS対応)

DEVELOP, Unity

何年も前に書いたものを記録。

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
 
namespace mira
{
    public class NotificationLocal
    {
        /// <summary>
        /// ローカルプッシュ通知の登録
        /// </summary>
        public static void Register(int id, long targetTime, string ticker, string contentTitle, string contentText)
        {
#if UNITY_EDITOR
            return;
#elif UNITY_IOS // iOS
            UnityEngine.iOS.LocalNotification n = new UnityEngine.iOS.LocalNotification();
            n.alertBody = contentText;
            n.applicationIconBadgeNumber = 1;
            n.fireDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(targetTime).ToLocalTime();
            n.hasAction = true;
            UnityEngine.iOS.NotificationServices.ScheduleLocalNotification(n);
#endif
        }
 
        /// <summary>
        /// 通知全削除
        /// </summary>
        public static void UnRegisterAll(int[] registerIds)
        {
#if UNITY_EDITOR
            return;
#elif UNITY_IOS
            UnityEngine.iOS.LocalNotification n = new UnityEngine.iOS.LocalNotification();
            n.alertAction = "";
            n.alertBody = "";
            n.applicationIconBadgeNumber = -1;
            n.fireDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(0).ToLocalTime();
            n.hasAction = false;
 
            // 直ぐに反映させることでバッジを削除
            UnityEngine.iOS.NotificationServices.PresentLocalNotificationNow(n);
            UnityEngine.iOS.NotificationServices.CancelAllLocalNotifications();
            UnityEngine.iOS.NotificationServices.ClearLocalNotifications();
#endif
        }
    }
}

Posted by kazupon