Reputation: 21
I'm having trouble with detecting the Firebase connection status with my Swift app. As soon as my view controller launches it immediately displays and alertView showing my connection status is down. It does this every time regardless of what the status actually is when the app starts. Once the app is started the connection status is reliably reported. Even when I switch to another view controller and back to the original one it doesn't report the connection as down again. It only happens when the app first launches. Here is the code where I have implemented my connection status detection in the viewDidLoad method. Does anyone have any suggestions?
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")
}
})
}
Upvotes: 2
Views: 2490
Reputation: 1038
My preferred method to handle this was to implement a shared instance which tracked the connection status. I had a isConnected
boolean which would toggle between true and false depending on the .info/connected
value, but I think it's also important to have another boolean, hasConnected
.
hasConnected
instantiates with false
, and isn't changed unless we received a connected result. This means when the app is first reporting it's disconnected results, you can check the hasConnected
boolean to determine if it's actually ever connected yet. You may want to simply disable your connection alerts until hasConnected
is 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
}
})
Let me know if there's anything you might want more information on.
Upvotes: 6