我正在使用Firebase Cloud Firestore,从存储中下载图像作为特定用户的profilePicture。
我可以为当前登录的currentUser设置图像,但是当我下载数据库中所有其他用户并为其设置图片时,所有用户UIImage变量的值总是以某种方式在数组中为nil。用户上的所有其他值都是有效的,因此必须与async保持一致?
我是初学者,非常感谢有人可以引导我朝正确的方向前进。
我以前使用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!)
}
}
}
答案 0 :(得分:0)
您只能在用户对象中保存url,并使用Kingfisher来管理此图像的下载 https://github.com/onevcat/Kingfisher
Example:
import Kingfisher
let resource = ImageResource(downloadURL: URL(fileURLWithPath: "YOUR_URL"))
self.imageView.kf.indicatorType = .activity
self.imageView.kf.setImage(with: resource, placeholder: #imageliteral))