这个问题可能是因为我对补全以及如何正确使用它们一无所知,但我一直在研究,只是找不到解决我的问题的方法。
我有一个从数据库中获取用户数据的函数,然后我想将从数据库中获取的值分配给我的表视图单元格。如果我的 AssignValueToUserObject 方法中没有完成,则在我实际获取导致错误的值之前调用我的表格视图单元格。
所以我发现完成是要走的路,到目前为止它对我有用,但是现在我使用的是表格视图单元格,我实际上无法在完成中手动调用表格视图方法,所以我不不知道如何使用该方法获取数据,然后将值分配给表格视图单元格。
这是我的方法:
extension MoneyGroupViewController {
public func AssignValueToUserObject(completion: @escaping () -> Void) {
// Get user unique id
guard let uid = Auth.auth().currentUser?.uid else {
print("Could not get user id")
return
}
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value,with: { [self] snapshot in
if let dictionary = snapshot.value as? [String: AnyObject] {
user.first_name = dictionary["first_name"] as! String
user.last_name = dictionary["last_name"] as! String
user.email = dictionary["email"] as! String
user.profile_picture = dictionary["profile_picture"] as? String
completion() //call once the action is done
}
},withCancel: nil)
} // End AssignValueToUserObject Method
} // End extension
这是我的表格视图单元格函数,它是我的视图控制器:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = groupTableView.dequeueReusableCell(withIdentifier: "MoneyGroupTableViewCell",for: indexPath) as! MoneyGroupTableViewCell
cell.username.text = userArray[indexPath.row].first_name + " " + userArray[indexPath.row].last_name
if (user.profile_picture != "") {
let url = URL(string: user.profile_picture!)!
URLSession.shared.dataTask(with: url,completionHandler: { data,_,error in
DispatchQueue.main.async {
cell.userImage.layer.cornerRadius = max(cell.userImage.frame.width,cell.userImage.frame.height)/2
cell.userImage.layer.borderWidth = 1
cell.userImage.image = UIImage(data: data!)
}
}).resume() // End URLSession
}
return cell
}
最后,这是我调用方法的方式:
override func viewDidLoad() {
super.viewDidLoad()
AssignValueToUserObject {
// I should call the table view function here but I don't know how
}
}
更新
是的,我的单元格应该显示用户的信息(名字、姓氏、电子邮件和可选的个人资料图片)。
我可能想在我的 userArray 中添加“组”中的所有用户,但现在我没有实现该功能,我只是在 userArray 中使用相同的用户来测试我的表视图。
所以 userArray 现在应该只有相同的用户,但我的问题仍然存在,我不知道如何在表格视图单元格调用之前从数据库中获取用户的信息。 >