调用完成处理程序Firebase Swift

时间:2018-05-14 00:06:01

标签: swift firebase firebase-realtime-database closures

从firebase检索单个值并获取它可能需要做很多工作,所以我可以在闭包之外使用它,但我似乎无法做出更简单的工作......

虽然我可能会或者可能没有创建一个像样的处理程序,但到目前为止它没有抛出任何错误,直到我尝试调用它然后我得到:无法将'String'类型的值转换为预期的参数类型'(String) - > ()'

答:如何调用该功能? B:有更简单的方法吗?

var myName = ""

func getMyName(completion: @escaping (String) -> ()){
    if let uid = Auth.auth().currentUser?.uid{
        databaseRef.child("bodhi").child((uid)).observeSingleEvent(of: .value, with: { (snapshot) in
            if let bodhiDict = snapshot.value as? [String: AnyObject]
            {
                let myName = (bodhiDict["Name"] as? String)!
                print ("myName in the closure: \(myName)")
                completion(myName)
            } else {
                completion("")
            }
        })
    }
}

getMyName(completion: (myName))
print ("myName Outside the closure: \(myName)")

1 个答案:

答案 0 :(得分:1)

您对getMyName的来电不正确。变化:

getMyName(completion: (myName))
print ("myName Outside the closure: \(myName)")

要么:

getMyName(completion: { (name) in
    print("Received \(name)")
})

或:

getMyName() { (name) in
    print("Received \(name)")
}

如您所见,您在函数外部声明的第一个myName变量是不必要的。