昨天實現(xiàn)了一下Unity里iOS推送。踩坑兩個。
1. 要先注冊推送才可以
接收推送前必須調(diào)用NotificationServices.RegisterForNotifications()才可以。否則接收不到推送。直接做iOS開發(fā)也是要注冊才可以的,Unity在設(shè)計的時候當然也要遵循iOS的接口啦。
2. 要設(shè)置推送的時區(qū)
在創(chuàng)建LocalNotification對象的時候,需要設(shè)置timeZone屬性。除非你是在GMT標準時區(qū)內(nèi)(比如大不列顛),否則時間會錯誤。
原本以為這個屬性應(yīng)該是個枚舉類型,但實際上是個字符串。搜了一下竟然沒有找到如何設(shè)置這個字符串。原生iOS開發(fā)這個是封裝過的,但Unity里沒有。還好機智的我嘗試了一下"GMT+8",沒想到一下就成功了。
最后貼一下代碼吧
首先是一個Singleton:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using iOSNS = UnityEngine.iOS.NotificationServices;
using iOSLocalNotification = UnityEngine.iOS.LocalNotification;
public class NotificationMgr
{
public const int NOTIF_MAX_DAY_NUM = 7;
private static NotificationMgr instance;
private NotificationMgr() {}
public static NotificationMgr GetInstance()
{
if (instance == null) {
instance = new NotificationMgr();
}
return instance;
}
public void FlushPlanNotification()
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
flushPlanNotificationIos();
}
private void flushPlanNotificationIos()
{
iOSNS.ClearLocalNotifications();
iOSLocalNotification notif = new iOSLocalNotification();
notif.alertBody = "推送文本";
notif.fireDate = info.alarmTime;
notif.timeZone = "GMT+8";
iOSNS.ScheduleLocalNotification(notif);
}
}
然后綁一個component腳本在一個GameObject上即可:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.iOS;
using iOSNS = UnityEngine.iOS.NotificationServices;
public class Notification : MonoBehaviour
{
void Start ()
{
iOSNS.RegisterForNotifications(NotificationType.Alert | NotificationType.Badge | NotificationType.Sound);
NotificationMgr.GetInstance().FlushPlanNotification();
}
}