Unity iOS本地推送踩坑实录

C#

浏览数:70

2019-8-30

昨天实现了一下Unity里iOS推送。踩坑两个。

1. 要先注册推送才可以

接收推送前必须调用NotificationServices.RegisterForNotifications()才可以。否则接收不到推送。直接做iOS开发也是要注册才可以的,Unity在设计的时候当然也要遵循iOS的接口啦。

2. 要设置推送的时区

在创建LocalNotification对象的时候,需要设置timeZone属性。除非你是在GMT标准时区内(比如大不列颠),否则时间会错误。
原本以为这个属性应该是个枚举类型,但实际上是个字符串。搜了一下竟然没有找到如何设置这个字符串。原生iOS开发这个是封装过的,但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();
    }
}

作者:Michaelbest1