我有一个用于用户个人资料图片的 UIImageView。但是,图像在屏幕上显示较晚,例如 2 到 3 秒。以下是我的下载方法:
@IBOutlet weak var ProfilePic: UIImageView!
override func awakeFromNib() {
FriendSystem.system.USER_REF.child(user.uid).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild("imageUrl"){
self.firebaseStorage.child("users").child(FriendSystem.system.CURRENT_USER_ID).getData(maxSize: 10*1024*1024, completion: { (data, error) in
let userPhoto = UIImage(data: data!)
self.ProfilePic.image = userPhoto
})
}
})
}
我该如何解决这个问题?
最佳答案
您正在运行的代码在不同的线程上运行,并且根据 Apple 的规定,所有 UI 更新都必须在主线程上运行。这是 link这解释了为什么所有 UI 更新都必须在主线程上
因此,在您的代码中,您只需像这样使用 DispatchQueue
DispatchQueue.main.async {
// please don't use implicit unwrapping of variables `data!` cause it may cause crashes, use if let statements instead
if let data = data {
let userPhoto = UIImage(data: data)
self.ProfilePic.image = userPhoto
}
}
换个说法:
关于ios - UIImage 在 viewController swift 上出现晚了 2-3 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46312077/