Skip to content

Instantly share code, notes, and snippets.

@ogrew
Last active January 27, 2023 06:30
Show Gist options
  • Save ogrew/fc991a419d78cb65a8775d0bc6e75488 to your computer and use it in GitHub Desktop.
Save ogrew/fc991a419d78cb65a8775d0bc6e75488 to your computer and use it in GitHub Desktop.
Unityローカルプッシュの実装(2023年)
// base : https://qiita.com/townsoft/items/dd5cbd8be7590e12f3cf
#if UNITY_ANDROID
using Unity.Notifications.Android;
#endif
#if UNITY_IOS
using Unity.Notifications.iOS;
#endif
using System;
public static class LocalPushNotificaion
{
/// <summary>
/// Androidではプッシュ通知用のチャンネルを登録する必要あり
/// </summary>
public static void RegisterChannel(string id, string title, string description)
{
#if UNITY_ANDROID
var c = new AndroidNotificationChannel()
{
Id = id,
Name = title,
Importance = Importance.High,
Description = description,
};
AndroidNotificationCenter.RegisterNotificationChannel(c);
#endif
}
public static void ClearAll()
{
#if UNITY_ANDROID
AndroidNotificationCenter.CancelAllScheduledNotifications();
AndroidNotificationCenter.CancelAllNotifications();
#endif
#if UNITY_IOS
iOSNotificationCenter.RemoveAllScheduledNotifications();
iOSNotificationCenter.RemoveAllDeliveredNotifications();
iOSNotificationCenter.ApplicationBadge = 0;
#endif
}
public static void AddSchedule(string title, string message, DateTime dt, string channelId)
{
#if UNITY_ANDROID
SetAndroidNotification(title, message, dt, channelId);
#endif
#if UNITY_IOS
var ps = new PushSchedule(dt);
SetIOSNotification(title, message, ps);
#endif
}
#if UNITY_IOS
static private void SetIOSNotification(string title, string message, DateTime dt)
{
var trigger = new iOSNotificationCalendarTrigger()
{
Year = dt.Year,
Month = dt.Month,
Day = dt.Day,
Hour = dt.Hour,
Minute = dt.Minute,
Second = dt.Second
};
var notification = new iOSNotification()
{
Identifier = $"_notification_01",
Title = title,
Body = message,
ShowInForeground = true,
Trigger = trigger
};
iOSNotificationCenter.ScheduleNotification(notification);
}
#endif
#if UNITY_ANDROID
static private void SetAndroidNotification(string title, string message, DateTime dt, string channel)
{
var notification = new AndroidNotification
{
title = title,
text = message,
fireTime = dt
};
AndroidNotificationCenter.SendNotification(notification, channel);
}
#endif
}
/// ----------------------------------------------------- ///
// using UnityEngine;
// using System;
// public class LocalPushScheduler : MonoBehaviour
// {
// void OnApplicationFocus() {
// SettingPush();
// }
// void SettingPush() {
// LocalPush.RegisterChannel("test", "mikubreak", "sample");
// LocalPush.ClearAll();
// var dt = new DateTime(2023, 1, 23, 19, 10, 0);
// LocalPush.AddSchedule("MIKUBREAKからのお知らせ", "みくみくにしてあげる♪", dt, "test");
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment