Unity iOS本地推送踩坑實錄

昨天實現(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();
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容