0
func RevisarConectividad() -> String
    {
        var Estado = ""
        let Referencia = Database.database().reference(withPath: ".info/connected")

        Referencia.observe(.value, with:
        { snapshot in
            if snapshot.value as? Bool ?? false
            {
                Estado = "Conectado"
            }
            else
            {
                Estado = "NoConectado"
            }
            print(Estado)
        })
        print("Estado:" + " " + Estado)
        return Estado


    }

I call it like:

let Estado = RevisarConectividad()

But for some reason, it seems Estado never took any of the both string. Anyway, I print "Estado" inside the closure and it is working, it prints its value correctly.

  • It is an asynchrony problem, this function returns immediately, while the function inside `.observe` is still not called, Firebase and Network connections must be handled using callbacks and completion handlers, not return values – user9335240 Oct 09 '18 at 18:27

2 Answers2

0

Assuming Database.observe is asynchronous, you're returning Estado with its initial value "" because the return Estado line runs before the actual assignment inside the observe closure.

Set breakpoints in return and in the assignments to Estado and see the execution order.

You need to use some asynchronous pattern: pass a closure to RevisarConectividad to be called when you have the data, or a delegate protocol, or KVO of some property...

djromero
  • 19,551
  • 4
  • 71
  • 68
0

"observe" is a Async func, when you return "estado" the value is not set it yet. You can pass a callback, and call it inside your function.

func RevisarConectividad(completion: @escaping (_ state:String) -> ())
{
    var Estado = ""
    let Referencia = Database.database().reference(withPath: ".info/connected")

    Referencia.observe(.value, with:
        { snapshot in
            if snapshot.value as? Bool ?? false
            {
                Estado = "Conectado"
            }
            else
            {
                Estado = "NoConectado"
            }
            completion(Estado)
    })
}

and then:

RevisarConectividad { (state) in
    print(state)
}
Kevinosaurio
  • 1,952
  • 2
  • 15
  • 18