【问题标题】:Trouble detecting Firebase connection status in Swift app在 Swift 应用程序中检测 Firebase 连接状态时遇到问题
【发布时间】:2016-05-31 02:45:33
【问题描述】:

我在使用 Swift 应用检测 Firebase 连接状态时遇到问题。一旦我的视图控制器启动,它就会立即显示,并且 alertView 显示我的连接状态已关闭。无论应用程序启动时的实际状态如何,它每次都会这样做。一旦应用程序启动,就会可靠地报告连接状态。即使我切换到另一个视图控制器并返回到原来的视图控制器,它也不会再次报告连接断开。它仅在应用程序首次启动时发生。这是我在 viewDidLoad 方法中实现连接状态检测的代码。有人有什么建议吗?

override func viewDidLoad() {

    //Do these things once when the app first starts up
    super.viewDidLoad()

    mapView.delegate = self

    setMapInitialState()

    let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
    connectedRef.observeEventType(.Value, withBlock: {snapshot in

        let connected = snapshot.value as? Bool
        if connected != nil && connected! {
            self.showAlertView("Alert", message: "Connection to server restored - all pending catches will be updated")
            self.refreshCatches()
        } else {
            self.showAlertView("Alert", message: "Connection to server lost - catches by others may not be up to date")
        }

    })

}

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    我首选的处理方法是实现一个跟踪连接状态的共享实例。我有一个 isConnected 布尔值,它会根据 .info/connected 值在真假之间切换,但我认为另一个布尔值 hasConnected 也很重要。

    hasConnectedfalse 实例化,除非我们收到连接的结果,否则不会更改。这意味着当应用程序首次报告其断开连接的结果时,您可以检查 hasConnected 布尔值以确定它是否实际上已经连接。您可能只想禁用连接警报,直到 hasConnected 变为 true

    let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
    connectedRef.observeEventType(.Value, withBlock: { (connected) in
        if let boolean = connected.value as? Bool where boolean == true {
            print("connected")
            self.hasConnected = true
            self.isConnected = true
        } else {
            print("disconnected")
            self.isConnected = false
        }
    })
    

    如果您想了解更多信息,请告诉我。

    【讨论】:

    • 那么条件是如何工作的?比如 if hasConnected && isConnected { // 已连接 } else { //未连接 } ???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2011-03-30
    相关资源
    最近更新 更多