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

iOS应用前台无法接收FCM消息,配置后回调未触发

解决iOS Firebase推送前台无通知、无回调的问题

我来帮你搞定这个Firebase推送的问题!你现在后台能正常收到通知,但前台没反应,核心原因是缺少iOS 10+前台通知的处理逻辑,还有一些配置细节没到位,具体修复步骤如下:

1. 确保AppDelegate遵守必要的协议

首先,你的AppDelegate需要同时遵守UNUserNotificationCenterDelegate和FIRMessagingDelegate协议,否则回调方法不会被触发。修改类声明:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {
    // 你的现有代码
}

2. 实现iOS 10+前台通知处理方法

对于iOS 10及以上系统,当App处于前台时,推送通知不会自动弹出,必须通过UNUserNotificationCenterDelegate的willPresent方法手动处理。添加这个方法到AppDelegate中:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // 这里可以获取并打印通知内容,处理业务逻辑
    let userInfo = notification.request.content.userInfo
    print("前台收到通知内容: \(userInfo)")
    
    // 如果想要前台弹出通知,就传入对应的展示选项,比如同时显示弹窗、角标和声音
    completionHandler([.alert, .badge, .sound])
}

这个方法是前台收到通知时的核心入口,你可以在这里自定义通知展示方式,或者直接触发业务逻辑。

3. 调整Firebase初始化顺序

你现在的代码是先注册远程通知,再初始化Firebase,这可能导致配置不生效。把FIRApp.configure()移到最前面,确保Firebase先完成初始化,再处理推送注册:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    // 先初始化Firebase
    FIRApp.configure()
    
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions, completionHandler: {_, _ in })
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    
    return true
}

4. 确认消息类型对应的回调

  • 如果服务器发送的是通知消息(包含alert字段):前台会触发上面的willPresent方法,后台会自动展示通知。
  • 如果服务器发送的是数据消息(只有自定义数据,没有alert字段):前台会触发applicationReceivedRemoteMessage方法,后台需要你手动处理(但后台数据消息的处理需要额外配置,不过你现在的问题是前台,所以先确保这个方法能被触发)。

做完这些修改后,重新运行App,前台就能收到通知并触发对应的回调了!

内容的提问来源于stack exchange,提问作者Shofiqul Alam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:18:49