我创建了一个函数,用于在userID参数上返回带有Firebase查询的用户名。我想使用此用户名填充tableView中的文本标签。虽然函数中的查询返回正确的值,但似乎没有返回值:
func getUser(userID: String) -> String {
var full_name: String = ""
rootRef.child("users").child(userID).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
let first_name = snapshot.value!["first_name"] as! String
let last_name = snapshot.value!["last_name"] as! String
full_name = first_name + " " + last_name
print(full_name) // returns correct value
})
return full_name //printing outside here just prints a blank space in console
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let inviteDict = invites[indexPath.row].value as! [String : AnyObject]
if let userID = inviteDict["invitedBy"] as? String {
let name = getUser(userID)
cell.textLabel!.text = name
}
return cell
}
}
细胞没有文字。打印功能返回控制台只打印空白区域。关于什么是错的任何想法?
谢谢!
答案 0 :(得分:1)
你的问题是你的getUser
函数执行一个块来获取full_name
值,但是你要在另一个线程上返回,所以当这行return full_name
执行时,几乎不可能您的块已结束,因此您的函数返回""
而不是您想要的值
试试这个
func getUser(userID: String,closure:((String) -> Void)?) -> Void {
var full_name: String = ""
rootRef.child("users").child(userID).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
let first_name = snapshot.value!["first_name"] as! String
let last_name = snapshot.value!["last_name"] as! String
full_name = first_name + " " + last_name
print(full_name) // returns correct value
closure(full_name)
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let inviteDict = invites[indexPath.row].value as! [String : AnyObject]
if let userID = inviteDict["invitedBy"] as? String {
let name = getUser(userID, closure: { (name) in
cell.textLabel!.text = name
})
}
return cell
}
我希望这会对你有所帮助,PS我不确定这是否有效,因为我没有这个图书馆