上個專案使用的簡易版iOS推送解決方案,記錄一下,以備后用
該方案需要注意iOS推送權限 Push Notifications
using UnityEngine;
using System.Collections;
#if UNITY_IPHONE
using NotificationServices = UnityEngine.iOS.NotificationServices;
using NotificationType = UnityEngine.iOS.NotificationType;
#endif
public class Nofication : MonoBehaviour {
//本地推送
public static void NotificationMessage(string message,int hour ,int min,int sec,bool isRepeatDay,string title)
{
int year = System.DateTime.Now.Year;
int month = System.DateTime.Now.Month;
int day= System.DateTime.Now.Day;
System.DateTime newDate = new System.DateTime(year,month,day,hour,min,sec);
NotificationMessage(message,newDate,isRepeatDay,title);
}
//本地推送 你可以傳入一個固定的推送時間
public static void NotificationMessage(string message,System.DateTime newDate,bool isRepeatDay,string title)
{
#if UNITY_IPHONE
//推送時間需要大于當前時間
if(newDate > System.DateTime.Now)
{
UnityEngine.iOS.LocalNotification localNotification = new UnityEngine.iOS.LocalNotification();
localNotification.fireDate =newDate;
localNotification.alertBody = message;
localNotification.applicationIconBadgeNumber = 1;
localNotification.hasAction = true;
localNotification.alertAction = title;
localNotification.alertTitle = title;//標題 注釋掉可以去掉標題
if(isRepeatDay)
{
//是否每天定期回圈
localNotification.repeatCalendar = UnityEngine.iOS.CalendarIdentifier.ChineseCalendar;
localNotification.repeatInterval = UnityEngine.iOS.CalendarUnit.Day;
}
localNotification.soundName = UnityEngine.iOS.LocalNotification.defaultSoundName;
UnityEngine.iOS.NotificationServices.ScheduleLocalNotification(localNotification);
}
#endif
}
void Awake()
{
DontDestroyOnLoad(gameObject);
//下面這段會調起iOS是否允許推送的授權提示框,可以放到自己想要授權的時機呼叫這段代碼
//是否彈出提示框由iOS系統判定,第一次拒絕后,長時間內不會主動再次彈出,
//開發者可以在iOS獲取授權狀態,自己做界面跳轉授權
#if UNITY_IPHONE
UnityEngine.iOS.NotificationServices.RegisterForNotifications(
NotificationType.Alert |
NotificationType.Badge |
NotificationType.Sound);
#endif
//第一次進入游戲的時候清空,有可能用戶自己把游戲從后臺殺死,這里強制清空
CleanNotification();
}
void OnApplicationPause(bool paused)
{
//程式進入后臺時
if(paused)
{
//10秒后發送
// NotificationMessage("這是notificationtest的推送正文資訊",System.DateTime.Now.AddSeconds(10),false);
//每天中午12點推送
NotificationMessage("推送內容1",11,55,0,true,"推送標題");
NotificationMessage("推送內容2",18,55,0,true,"推送標題");
}
else
{
//程式從后臺進入前臺時
CleanNotification();
}
}
//清空所有本地訊息
public static void CleanNotification()
{
#if UNITY_IPHONE
UnityEngine.iOS.LocalNotification l = new UnityEngine.iOS.LocalNotification ();
l.applicationIconBadgeNumber = -1;
UnityEngine.iOS.NotificationServices.PresentLocalNotificationNow (l);
UnityEngine.iOS.NotificationServices.CancelAllLocalNotifications ();
UnityEngine.iOS.NotificationServices.ClearLocalNotifications ();
#endif
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/289403.html
標籤:其他
上一篇:Unity UGUI原始碼決議
下一篇:猜數字小游戲(C語言版)
