0
let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
   if snapshot.value as? Bool ?? false {
      print("Connected")
   } else {
      print("Not connected")
   }
})

I'm using this to detect my connection state to my firebase. My problem is when their is internet connection the result goes "Not Connected" then afterwards goes "Connected". When their is no internet connection it just goes directly to "Not Connected". Can someone please explain?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
jay123456
  • 131
  • 1
  • 1
  • 10
  • Can provide signature of func `observe`? If there is a `change` parameter, then it might be called with `old` and then `new` value – Modo Ltunzher Jul 05 '18 at 10:02
  • Why not just return the new value? Old value is not useful to begin with. – jay123456 Jul 05 '18 at 10:20
  • I don't know how this function works in your sample, but it looks like KVO, and KVO allows you to observe property changes "from-to", "from", "to" etc. In newer KVO API there is an object in parameter to observation block and it encapsulated old value, new value and change type, thus is called once. Also this logic is used in UIGestureRecognizer, when sinple handler is called multiple times, and developer should handle recognizer.state - i.e. ist started, changed, ended or failed. – Modo Ltunzher Jul 05 '18 at 12:26

1 Answers1

0

What you're seeing is the expected behavior.

The .info/connected flag determines whether the app/client is connected to the Firebase Database backend. While this of course requires that you have an internet connection, there is more to it than that. That's why it is possible for .info/connected to be false even though you have a working internet connection.

This is especially true when you start the app. It takes a few moments after the app starts before the Firebase client is connected to its database server, so usually the .info/connected value starts as false and then becomes true. Sometimes it even toggles a few times before settling.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807