我正在尝试从仪表板中获取UserProfile节点中的一些值,并将它们传递给全局变量,以便在observe函数之外全局使用它们。
ref.child("UserProfile").child(FIRAuth.auth()!.currentUser!.uid).observeEventType(.Value , withBlock: {snapshot in
if let name = snapshot.value!.objectForKey("name") as? String {
print(name)
}
if let email = snapshot.value!.objectForKey("email") as? String {
print(email)
}
if let phone = snapshot.value!.objectForKey("phone") as? String {
print(phone)
}
if let city = snapshot.value!.objectForKey("city") as? String {
print(city)
}
})
我想将它们传递给observe函数之外,这样我就可以在.swift文件中的任何地方全局使用它们。
答案 0 :(得分:2)
由于Firebase函数应该是异步,因此您需要在函数的completionBlock中访问这些User属性。并且请注意,一旦呼叫完成,他们将只提供检索到的值。
var globalUserName : String!
var globalEmail : String!
var globalPhone : String!
var globalCity : String!
override func viewWillAppear(animated : Bool){
super.viewWillAppear(animated)
retrieveUserData{(name,email,phone,city) in
self.globalUserName = name
self.globalEmail = email
self.globalPhone = phone
self.globalCity = city
}
}
func retrieveUserData(completionBlock : ((name : String!,email : String!, phone : String!, city : String!)->Void)){
ref.child("UserProfile").child(FIRAuth.auth()!.currentUser!.uid).observeEventType(.Value , withBlock: {snapshot in
if let userDict = snapshot.value as? [String:AnyObject] {
completionBlock(name : userDict["name"] as! String,email : userDict["email"] as! String, phone : userDict["phone"] as! String, city : userDict["city"] as! String)
}
})
}