PAYATHON 2026

Xamarin iOS 16/17 无法显示 Firebase 推送通知或警报

排障赵师傅

结论

拿到 Firebase registration token,只能说明 Firebase 生成了 token。iOS 是否允许通知,以及 FCM token 是否已与当前设备的 APNs token 正确关联,还需要分别确认。

排查时应检查以下环节:

  1. 应用是否请求并获得了通知权限。
  2. 应用是否成功向 APNs 注册。
  3. APNs token 是否已交给 Firebase Messaging。
  4. 签名后的应用是否包含正确的 aps-environment entitlement。
  5. Firebase 中的 Bundle ID、APNs key 是否与应用签名匹配。
  6. 应用在前台收到通知时,是否通过 UNUserNotificationCenterDelegate 指定了显示方式。
  7. 消息负载是否包含显示通知所需的 aps.alert。

UIAlertController 和 Xamarin.Forms 的 DisplayAlert 是应用内界面,不受 APNs、Firebase 或系统通知权限控制。如果这两种弹窗也无法显示,应另查 UI 线程、当前页面以及正在显示的 UIViewController,不要将其与推送配置问题混在一起排查。

先确认通知权限和 APNs 注册

应用启动后应请求通知权限。用户授权后,再调用 RegisterForRemoteNotifications():

using Foundation;
using UIKit;
using UserNotifications;

public override bool FinishedLaunching(
    UIApplication application,
    NSDictionary launchOptions)
{
    Firebase.Core.App.Configure();

    UNUserNotificationCenter.Current.Delegate =
        new UserNotificationCenterDelegate();

    UNUserNotificationCenter.Current.RequestAuthorization(
        UNAuthorizationOptions.Alert |
        UNAuthorizationOptions.Badge |
        UNAuthorizationOptions.Sound,
        (granted, error) =>
        {
            Console.WriteLine($"Notification permission granted: {granted}");
            Console.WriteLine($"Permission error: {error}");

            if (granted)
            {
                BeginInvokeOnMainThread(() =>
                {
                    UIApplication.SharedApplication
                        .RegisterForRemoteNotifications();
                });
            }
        });

    return base.FinishedLaunching(application, launchOptions);
}

同时记录 APNs 的注册结果:

public override void RegisteredForRemoteNotifications(
    UIApplication application,
    NSData deviceToken)
{
    Console.WriteLine($"APNs token: {deviceToken}");

    // 如果 Firebase 自动方法交换已关闭,需要手动设置。
    Messaging.SharedInstance.ApnsToken = deviceToken;
}

public override void FailedToRegisterForRemoteNotifications(
    UIApplication application,
    NSError error)
{
    Console.WriteLine(
        $"APNs registration failed: {error.LocalizedDescription}");
}

Messaging 的命名空间和属性名称可能因 Xamarin Firebase binding 包而异。上例采用常见的 Messaging.SharedInstance.ApnsToken 写法,实际使用时应以项目引用的 binding API 为准。

如果没有进入 RegisteredForRemoteNotifications,说明问题仍在设备权限、应用签名或 APNs 注册阶段,此时不用先查服务器的消息内容。

前台通知可能不会显示横幅

应用位于前台时,iOS 通常会将通知交给应用处理,不会自动显示横幅。需要实现 UNUserNotificationCenterDelegate:

using Foundation;
using UserNotifications;

public sealed class UserNotificationCenterDelegate
    : UNUserNotificationCenterDelegate
{
    public override void WillPresentNotification(
        UNUserNotificationCenter center,
        UNNotification notification,
        Action<UNNotificationPresentationOptions> completionHandler)
    {
        Console.WriteLine(
            $"Foreground notification: {notification.Request.Content.UserInfo}");

        completionHandler(
            UNNotificationPresentationOptions.Alert |
            UNNotificationPresentationOptions.Badge |
            UNNotificationPresentationOptions.Sound);
    }

    public override void DidReceiveNotificationResponse(
        UNUserNotificationCenter center,
        UNNotificationResponse response,
        Action completionHandler)
    {
        Console.WriteLine(
            $"Notification opened: {response.Notification.Request.Content.UserInfo}");

        completionHandler();
    }
}

测试时也要将应用切到后台,或锁定屏幕。通过对比测试,可以判断消息是没有送达,还是已经送达但未在前台显示。

检查设备上的实际授权状态

可以直接读取系统保存的通知设置:

UNUserNotificationCenter.Current.GetNotificationSettings(settings =>
{
    Console.WriteLine($"AuthorizationStatus: {settings.AuthorizationStatus}");
    Console.WriteLine($"AlertSetting: {settings.AlertSetting}");
    Console.WriteLine($"SoundSetting: {settings.SoundSetting}");
    Console.WriteLine($"BadgeSetting: {settings.BadgeSetting}");
});

如果状态为 Denied,再次调用授权 API 不会重新弹出系统询问框。需要让用户前往:

设置 > 通知 > 应用名称 > 允许通知

还要确认通知中心、锁定屏幕和横幅均已启用。专注模式、定时摘要以及设备管理策略也可能延迟或隐藏通知。

这些设置不会阻止应用显示 UIAlertController 或 DisplayAlert。如果系统通知和应用内弹窗都没有出现,应先确认弹窗代码是否实际执行。

检查签名后的 entitlement

即使 Entitlements.plist 中写有 aps-environment,最终安装包也未必带有该权限。应直接检查签名后的 .app:

codesign -d --entitlements :- /path/to/MyApp.app

开发调试包通常应包含:

<key>aps-environment</key>
<string>development</string>

TestFlight、App Store 或使用生产分发配置签名的构建通常应包含:

<key>aps-environment</key>
<string>production</string>

不要直接将该值固定为 production。它必须与签名证书、provisioning profile 和构建类型一致。修改 App ID 的 Push Notifications capability 后,还需要重新生成并安装 provisioning profile,再重新构建应用。

同时核对以下配置:

  • Apple Developer 中 App ID 的 Bundle ID 与应用完全一致。
  • provisioning profile 属于同一个 App ID,并包含 Push Notifications capability。
  • Firebase 项目中 iOS App 的 Bundle ID 与应用一致。
  • GoogleService-Info.plist 来自正确的 Firebase iOS App。
  • GoogleService-Info.plist 的 Build Action 是 BundleResource,而且该文件确实进入了应用包。
  • Firebase 中上传的 APNs private key、Key ID 和 Team ID 属于正确的 Apple Developer Team。
  • 应用没有同时加载其他环境或其他 Bundle ID 的 Firebase 配置文件。

使用 APNs authentication key 时,同一把有效密钥通常可以同时用于开发和生产 APNs 环境,但应用仍须使用正确的 profile 签名。

确认 APNs token 与 Firebase token 已正确关联

FCM token 和 APNs token 是两个不同的标识。打印出 FCM token,并不能证明整个 iOS 推送链路已经接通。

如果关闭了 Firebase App Delegate swizzling,例如在 Info.plist 中配置:

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

应用必须手动将 APNs token 设置给 Firebase Messaging。否则,即使服务器已成功向 FCM token 发送消息,也可能无法将消息投递到对应的 APNs 设备。

没有特殊需求时,建议保留 Firebase 的自动方法交换。如果必须关闭,应按照当前 Xamarin Firebase binding 的文档,手动转发 APNs token 和通知回调。

每次重新安装应用、切换签名环境或更换 Firebase 配置后,都要重新获取并上传最新的 FCM token,不要继续使用旧安装生成的 token。

确认消息负载能够显示通知

纯 data 消息不会自动显示横幅。要让 iOS 显示通知,APNs payload 必须包含 aps.alert。下面是一个 Firebase HTTP v1 消息示例:

{
  "message": {
    "token": "FCM_REGISTRATION_TOKEN",
    "apns": {
      "headers": {
        "apns-push-type": "alert",
        "apns-priority": "10"
      },
      "payload": {
        "aps": {
          "alert": {
            "title": "测试通知",
            "body": "这是一条 iOS 测试消息"
          },
          "sound": "default"
        }
      }
    }
  }
}

如果消息只有以下内容:

{
  "aps": {
    "content-available": 1
  }
}

这是一条后台更新消息,不会显示通知横幅。后台静默推送还会受到应用状态、Background Modes 和系统调度策略的影响,不适合用来验证可见通知。

排查初期先发送最简单的 alert 消息。确认前台、后台和锁屏状态下都能正常接收后,再添加自定义数据字段。

单独排查 UIAlertController

原生弹窗必须在主线程中,由当前可见的 UIViewController 调用:

InvokeOnMainThread(() =>
{
    var alert = UIAlertController.Create(
        "测试",
        "UIAlertController 可以正常显示",
        UIAlertControllerStyle.Alert);

    alert.AddAction(UIAlertAction.Create(
        "确定",
        UIAlertActionStyle.Default,
        null));

    var controller = GetVisibleViewController(
        UIApplication.SharedApplication
            .KeyWindow?
            .RootViewController);

    controller?.PresentViewController(alert, true, null);
});

查找当前可见的控制器时,需要处理导航页、标签页以及已经弹出的控制器:

private UIViewController GetVisibleViewController(
    UIViewController controller)
{
    if (controller == null)
        return null;

    if (controller.PresentedViewController != null)
        return GetVisibleViewController(
            controller.PresentedViewController);

    if (controller is UINavigationController navigationController)
        return GetVisibleViewController(
            navigationController.VisibleViewController);

    if (controller is UITabBarController tabBarController)
        return GetVisibleViewController(
            tabBarController.SelectedViewController);

    return controller;
}

在多窗口应用中,KeyWindow 可能为空,也可能不是当前活动窗口。此时应从活动的 UIWindowScene 获取前台窗口,不要长期保存旧的 UIViewController 引用。

单独排查 Xamarin.Forms DisplayAlert

Xamarin.Forms 的 DisplayAlert 应由当前活动页面在主线程中调用:

Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
{
    var page = Xamarin.Forms.Application.Current?.MainPage;

    if (page != null)
    {
        await page.DisplayAlert(
            "测试",
            "DisplayAlert 可以正常显示",
            "确定");
    }
});

如果登录后替换了 Application.Current.MainPage,需要确认发起弹窗的对象仍在当前页面树中。常见原因有:

  • 直接从后台线程调用 UI API。
  • 使用了已经被替换或释放的页面。
  • 在页面尚未显示时调用弹窗。
  • 另一个模态页面正在执行切换动画。
  • async void 中发生异常,却没有记录该异常。
  • WebView 导航或登录完成回调没有切回主线程。

可以在登录完成后直接显示一个内容固定的测试弹窗。如果仍然没有出现,应先处理页面生命周期或线程问题,无须继续修改 Firebase 配置。

建议的定位顺序

按以下顺序检查,通常可以较快判断故障所在的环节:

  1. 启动后读取 AuthorizationStatus,确认系统已经授权。
  2. 确认进入 RegisteredForRemoteNotifications,并记录 APNs token。
  3. 确认 Firebase Messaging 获得了新的 FCM token。
  4. 检查签名后的 .app 中是否实际存在 aps-environment。
  5. 使用 Firebase Console,向当前安装生成的 FCM token 发送测试通知。
  6. 将应用置于后台或锁屏后测试。
  7. 实现 WillPresentNotification,然后测试前台通知。
  8. 使用包含 aps.alert 的最小消息负载测试服务器发送。
  9. 在主线程直接调用内容固定的 DisplayAlert,单独验证 UI 弹窗。

Xcode 14.3 使用的是 iOS 16 时代的 SDK,未必会直接导致通知故障。在 iOS 17 设备上排查时,仍要确认 Visual Studio、Xamarin.iOS、Xcode 和 macOS 的版本组合彼此兼容。升级工具链后,需要重新生成、签名并安装应用,以免旧构建或旧 provisioning profile 影响测试结果。

备注:内容仅供参考。