Firebase检索并将数据传递给变量

时间:2016-03-10 16:11:26

标签: ios swift firebase

ridvankucuk Problem

func getHandleStatus() -> String {
    var handle = String()
    ref.queryOrderedByChild("status").observeEventType(.ChildAdded, withBlock: { snapshot in
        if let status = snapshot.value["status"] as? Int {
            if status == 0 {
                //print(snapshot.key)
                handle = snapshot.key
            } else {
                print("NO")
            }
        }
    })
    return handle
}

当我返回" handle"时,它总是空字符串。我设置变量" handle = snapshot.key"当我回来时,它仍然是空的。请帮忙。

1 个答案:

答案 0 :(得分:0)

首先,你的方法是异步的,它不是在等待主线程。所以写回报毫无意义。你应该做点什么。 在函数之外定义变量,例如:

var handle: String? = nil {
        didSet{
            // You know handle is set now
        }
    }

并更新你的getHandleStatus方法:

func getHandleStatus(){
    var handle = String()
    ref.queryOrderedByChild("status").observeEventType(.ChildAdded, withBlock: { snapshot in
        if let status = snapshot.value["status"] as? Int {
            if status == 0 {
                //print(snapshot.key)
                self.handle = snapshot.key
            } else {
                print("NO")
            }
        }
    })
}