You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity iOS端从推送启动时iOSNotificationCenter.GetLastRespondedNotification()返回null

Unity iOS冷启动时获取推送通知数据的解决方案

你用的iOSNotificationCenter.GetLastRespondedNotification()确实只适用于应用从后台唤醒的场景,当应用被彻底关闭(冷启动)时,这个方法返回null是正常的——因为冷启动时通知数据会被传递到应用的启动参数里,而不是iOSNotificationCenter的响应队列中。

结合你用Playfab推送的场景,解决方法需要区分两种启动状态分别处理:


1. 处理冷启动场景(彻底关闭后点击通知启动)

冷启动时,推送数据会被iOS封装到启动参数中,Unity提供了UnityEngine.iOS.NotificationServices类来读取这部分数据。

在应用启动的第一个脚本(比如挂载在初始场景的常驻物体上)中添加以下逻辑:

using UnityEngine;
using UnityEngine.iOS;

public class PushNotificationManager : MonoBehaviour
{
    void Awake()
    {
        // 检查是否有冷启动时的远程通知
        if (NotificationServices.remoteNotificationCount > 0)
        {
            var launchNotification = NotificationServices.GetRemoteNotification(0);
            if (launchNotification != null)
            {
                // 获取通知的基本内容
                string alertTitle = launchNotification.alertTitle;
                string alertBody = launchNotification.alertBody;

                // 提取Playfab推送的自定义数据(存在userInfo字典中)
                if (launchNotification.userInfo != null)
                {
                    foreach (var key in launchNotification.userInfo.Keys)
                    {
                        string value = launchNotification.userInfo[key].ToString();
                        // 这里替换成你处理自定义数据的逻辑
                        Debug.Log($"冷启动通知自定义字段: {key} = {value}");
                    }
                }
            }
        }
    }
}

2. 处理后台唤醒场景(应用在后台点击通知唤醒)

这部分你原来的方法是有效的,建议和冷启动逻辑整合在一起:

void Awake()
{
    // ... 上面的冷启动逻辑 ...

    // 处理后台唤醒的通知
    var lastRespondedNotification = iOSNotificationCenter.GetLastRespondedNotification();
    if (lastRespondedNotification != null)
    {
        string title = lastRespondedNotification.Title;
        string body = lastRespondedNotification.Body;

        // 提取自定义数据
        if (lastRespondedNotification.Data != null)
        {
            foreach (var kvp in lastRespondedNotification.Data)
            {
                Debug.Log($"后台唤醒通知自定义字段: {kvp.Key} = {kvp.Value}");
            }
        }
    }
}

3. 关键配置注意事项

  • Playfab推送Payload格式:确保推送的自定义数据被正确放在APNs的userInfo字段中(Playfab后台配置推送时,自定义参数会自动映射到这里),这样Unity才能通过userInfo或Data字段读取到。
  • iOS权限配置:在Unity Player Settings的iOS选项中,启用Remote Notifications权限;同时在Xcode的Capabilities中打开Push Notifications开关。
  • 脚本执行时机:确保处理通知的脚本在应用启动时最早执行(比如设置脚本的Execution Order为最早),避免错过启动参数中的通知数据。

内容的提问来源于stack exchange,提问作者Arnav Sanghavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:35:16