1

I want to be able to perform a selector as soon the user disconnect from Firebase unexpectedly (maybe because of internet connection, battery died, etc). I believe I came across a function that did just that, but I can't find it. Thank you in advance.

AL.
  • 36,815
  • 10
  • 142
  • 281
SwiftER
  • 1,235
  • 4
  • 17
  • 40
  • I'm not sure you can perform selectors on Firebase, so I asume you want to do it on swift despite the fact I can't understand how it is posible if the phone is off. So just to be clear: you want to perform selector on your code or you want to trigger some action on firebase? – i6x86 Feb 02 '17 at 00:44

2 Answers2

1
let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
        connectedRef.observe(.value, with: { snapshot in
            if let connected = snapshot.value as? Bool, connected {
                print("Connected")
            } else {
                print("Not connected")
            }
        })
SwiftER
  • 1,235
  • 4
  • 17
  • 40
0

What you need is a way to handle the connection errors and this is a very specific depending on the architecture of your app, but I'll tell how I did it in an app that is still on production.

So if you search on google how to do this you'll find that you can use Reachability, it seems there are some solution with Alamofire too, but I used this simplest way. I wrote a func that runs similar to this code:

func checkInternet() {
    DispatchQueue.main.async {
        let url = URL(string: "https://www.google.com")!
        let request = URLRequest(url: url)

        let task = URLSession.shared.dataTask(with: request) {data, response, error in

            if error != nil {

                print("Internet Connection not Available!")
                self.haveInternetConnection = false
            }
            else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                print("Internet Connection OK")
                }
                print("statusCode: \(httpResponse.statusCode)")
            }

        }
        task.resume()
    }

}

And there, every time I need to check if there's still active connection I use it. Also I found the solution here: https://stackoverflow.com/a/41271535/5843195

Edit: Personally, i think is better to check if there's a connection at all, rather than if there's a connection to the Database.

Community
  • 1
  • 1
i6x86
  • 1,557
  • 6
  • 23
  • 42