【发布时间】:2019-09-13 21:39:40
【问题描述】:
我正在使用 firebase cloud firestore,从他们的存储中下载图像作为特定用户的 profilePicture。
我可以为当前登录的 currentUser 设置图像,但是当我下载并设置数据库中所有其他用户的图片时,所有用户 UIImage 变量的值总是以某种方式在数组中为零。用户的所有其他值都是有效的,所以它必须是异步的?
我是初学者,如果有人能指导我正确的方向,我将不胜感激。
我以前用 tableView 做过这个,效果很好,但现在不能......
func loadAllUsersFromDB() {
db.collection("users").getDocuments { (snapshot, error) in
if error != nil {
print(error!)
} else {
for document in snapshot!.documents {
if let snapshotValue = document.data() as? [String : Any] {
let userId = snapshotValue["userID"] as? String
if userId == self.currentUID {
self.currentUser.firstName = snapshotValue["firstname"] as? String
self.currentUser.lastName = snapshotValue["lastname"] as? String
self.currentUser.email = snapshotValue["email"] as? String
self.currentUser.uid = snapshotValue["userID"] as? String
self.currentUser.aboutUser = snapshotValue["aboutUser"] as? String
self.currentUser.aboutDog = snapshotValue["aboutUserDog"] as? String
let photoURL = snapshotValue["photoURL"] as? String
if let url = URL(string: photoURL!) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async {
self.currentUser.profilePhoto = UIImage(data: data!)
}
}
}
} else {
self.user.firstName = snapshotValue["firstname"] as? String
self.user.lastName = snapshotValue["lastname"] as? String
self.user.email = snapshotValue["email"] as? String
self.user.uid = snapshotValue["userID"] as? String
self.user.aboutUser = snapshotValue["aboutUser"] as? String
self.user.aboutDog = snapshotValue["aboutUserDog"] as? String
let photoURL = snapshotValue["photoURL"] as? String
if let url = URL(string: photoURL!) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async {
self.user.profilePhoto = UIImage(data: data!)
}
}
}
self.allUsersArray.append(self.user)
}
}
}
self.checkIfUserIsFriends()
}
self.filterUsersToShow()
}
}
这行代码有效,并将下载的照片添加到 currentUser,我可以将 currentUser.profilePhoto 中的图像设置为另一个 ViewController 上的 imageView。
let photoURL = snapshotValue["photoURL"] as? String
if let url = URL(string: photoURL!) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async {
self.currentUser.profilePhoto = UIImage(data: data!)
}
}
}
}
但是当我将用户添加到数组时,用户的 profilePhoto 总是为零。
let photoURL = snapshotValue["photoURL"] as? String
if let url = URL(string: photoURL!) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async {
self.user.profilePhoto = UIImage(data: data!)
}
}
}
【问题讨论】:
标签: swift firebase google-cloud-firestore uiimage dispatch-async