ios - Firebase Messaging shouldEstablishDirectChannel 未在首次应用启动时建立连接

标签 ios swift sockets firebase firebase-cloud-messaging

问题

首次启动应用程序时,或删除并重新安装后,Messaging.messaging().shouldEstablishDirectChannel 不会建立套接字连接。如果我关闭应用程序并重新打开它,则会建立套接字连接。

重现步骤:

1) 将这段代码放在 AppDelegate 中: FirebaseApp.configure() Messaging.messaging().delegate = self Messaging.messaging().shouldEstablishDirectChannel = true

2) 将此代码放在后面的任何位置以检查是否建立了连接: Messaging.messaging().isDirectChannelEstablished 这总是返回 false。

3) 监听连接状态变化并观察这个通知永远不会被触发。 NotificationCenter.default.addObserver(自身,选择器: #选择器(fcmConnectionStateChange),名称: NSNotification.Name.MessagingConnectionStateChanged,对象:无)

简而言之,这就是问题所在。如果我简单地终止该应用程序并重新启动它,一切都会按预期进行。建立套接字连接并触发 MessagingConnectionStateChanged 通知。

为什么 Messaging.messaging().shouldEstablishDirectChannel 在我的初始应用启动时没有连接?

相关代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window!.rootViewController = RootViewController.shared
        window!.makeKeyAndVisible()
        setUpFirebase()
        setUpPushNotificationsForApplication(application)
        RootViewController.shared.goToLoginVC()

        return true
    }

    // MARK: - Firebase

    func setUpFirebase() {
        NotificationCenter.default.addObserver(self, selector:
            #selector(fcmConnectionStateChange), name:
            NSNotification.Name.MessagingConnectionStateChanged, object: nil)        
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        Messaging.messaging().shouldEstablishDirectChannel = true
    }

    // MARK: - Firebase Notifications

    func fcmConnectionStateChange() {
       // This is never called on app's first launch!!!
        print(Messaging.messaging().isDirectChannelEstablished)
    }

环境

  • Xcode 版本:8.3.3
  • Firebase 4.1.0
  • FirebaseAnalytics 4.0.3
  • FirebaseCore 4.0.5
  • FirebaseInstanceID 2.0.1
  • FirebaseMessaging 2.0.1
  • Firebase 产品:消息传递

最佳答案

在获得 token 之前尝试 FCM 连接可能会失败。

我修改了你的代码,试试这个。

func setUpFirebase() {
    NotificationCenter.default.addObserver(self, selector: 
        #selector(self.tokenRefreshNotification), name: 
        NSNotification.Name.InstanceIDTokenRefresh, object: nil)
    NotificationCenter.default.addObserver(self, selector:
        #selector(self.fcmConnectionStateChange), name:
        NSNotification.Name.MessagingConnectionStateChanged, object: nil)        
    FirebaseApp.configure()
    Messaging.messaging().delegate = self
}

func tokenRefreshNotification(_ notification: Notification) {
    if let refreshedToken = InstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
    }

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        return;
    }
    Messaging.messaging().shouldEstablishDirectChannel = true
}

func fcmConnectionStateChange() {
    if Messaging.messaging().isDirectChannelEstablished {
        print("Connected to FCM.")
    } else {
        print("Disconnected from FCM.")
    }
}

更新: 在使用 NotificationCenter 之前添加它。

    if #available(iOS 10, *) {
        print("iOS 10 up")
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            guard error == nil else {
                print("regist fail = \(String(describing: error))")
                return
            }
            if granted {
                print("allow regist")
            } else {
                //Handle user denying permissions..
                print("deny regist")
            }
        }
    } else {
        print("iOS 9 down")
        let pushNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings( pushNotificationSettings )
    }
    application.registerForRemoteNotifications()

关于ios - Firebase Messaging shouldEstablishDirectChannel 未在首次应用启动时建立连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828528/

相关文章:

sockets - 有一个多ip接口(interface)。如何选择其中一个来建立传出连接?

ios - 将对象解析为 AnnonationPoints

ios - Facebook-由app_scoped_user_id打开个人资料

ios - 在 UIWebview,iOS 中自动播放视频

ios - 从 iOS 应用程序处理飞行模式开/关状态

c - 套接字事务未通过

iphone - 调用 block 中的方法?

ios - 何时使用 swift 初始化 viewController 全局变量

swift - SQLite.swift 和 Swift 3 "Ambiguous reference to member =="加入

python - socket编程中如何选择端口?