【问题标题】:FCM and iOS - Message only received when switching to foreground or reopening the appFCM 和 iOS - 仅在切换到前台或重新打开应用程序时收到消息
【发布时间】:2018-05-28 10:37:17
【问题描述】:

你好 stackoverflow 社区!

我在使用 iOS 和 FCM 时遇到了一些问题:当我第一次启动应用程序时,没有收到 FCM 消息。如果我

  • 关闭应用并再次打开或
  • 再次将应用切换到后台和前台,

突然收到所有消息。之后,该应用程序运行良好 - 只是第一次无法正常运行。 唯一有帮助的是将“FirebaseInstanceID”降级为“2.0.0”。 其他 Firebase Pod 是

  • Firebase 4.13.0
  • FirebaseAnalytics 4.2.0
  • FirebaseAuth 4.6.1
  • FirebaseCore 4.0.20
  • FirebaseCrash 2.0.2
  • FirebaseInstanceID 2.0.0
  • FirebaseMessaging 2.2.0

XCode 是版本 9.3 (9E145)

我的 AppDelegate 与 didFinishLaunchingWithOptions 有

FMessaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true

FirebaseApp.configure()

application.registerForRemoteNotifications()

我也有

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

     Messaging.messaging().apnsToken = deviceToken
}

我用

extension AppDelegate : MessagingDelegate {

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    ...
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
...
}

这是一种常见的行为/错误还是我在这里做错了什么?

非常感谢!

【问题讨论】:

    标签: ios swift firebase firebase-cloud-messaging


    【解决方案1】:

    此 FCM 应注册到后台模式。您应该允许它在后台运行。

    1/ 在您的项目功能中启用后台模式并选择您使用的选项(后台获取、远程通知)

    2/ 在 appdelegate 中: - 声明:var backgroundTask: UIBackgroundTaskIdentifier?。 - 将此添加到 applicationDidEnterBackground

      backgroundTask = application.beginBackgroundTask(withName: "Task", expirationHandler: {
                    application.endBackgroundTask(self.backgroundTask!)
                    self.backgroundTask = UIBackgroundTaskInvalid
                })
    

    【讨论】:

    • 您好,感谢您的回答,但后台模式实际上不是问题。正如我所指出的,在 FOREGROUND 模式下不会收到消息,如果我切换到后台然后再次切换到前台,则会收到 FCM 消息。在我这样做之后,FCM 消息传递工作正常。
    • 我完全了解你的情况。我尝试了我的方式,它的工作正常。我认为您应该再次检查您的 deviceToken,因为有时在您第一次安装应用程序时未从 Firebase 收到 deviceToken =>您无法收到 FCM。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2019-06-28
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多