【发布时间】:2021-08-01 18:03:53
【问题描述】:
可能会因为我对完成以及如何正确使用它们的无知而提出这个问题,但是我一直在研究并且找不到解决我的问题的方法。
我有一个从数据库获取用户数据的函数,然后我想将从数据库获取的值分配给我的表格视图单元格。如果我的 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 现在应该只有同一个用户,但我的问题仍然存在,我不知道如何在 表格视图单元格调用之前从数据库中获取用户信息。 p>
【问题讨论】:
-
显示
userArray的定义以及如何填充它。简短的回答是,在表格视图准备好显示之前,您无法从数据库中获取或下载图像。您需要显示一个空的表格视图或带有占位符信息的单元格,直到您能够加载所需的数据。 -
如果您的目标是显示用户列表及其信息,请不要先将其编写为与单个用户一起使用,然后再返回并更改以稍后管理多个用户。处理用户列表时会遇到一些问题,如果你这样做,以后会咬你。你最终需要彻底重写。
-
我明白你的意思,我会听取你的建议,并会首先尝试管理多个用户。那么在加载数据之前,我将如何实现显示空表视图或带有占位符的单元格呢?您介意发布一个表明这一点的答案吗?
-
Firebase 有多种不同的数据库服务。因此,使用 firebase 标记并不能告诉我们您正在使用哪种服务。
-
我不确定您指的是什么不同的服务,但我使用的是实时数据库。