我试图从我的firebase数据库下载图像并将它们加载到collectionviewcells中。图像下载,但我有麻烦让他们都下载和异步加载。异步下载和缓存来自url的图像
当前当我运行我的代码最后图像下载加载。但是,如果我更新数据库,集合视图更新和新的最后一个用户配置文件图像也会加载,但其余部分不存在。
我宁愿不使用第三方库,所以任何资源或建议将不胜感激。
下面是处理下载的代码:
func loadImageUsingCacheWithUrlString(_ urlString: String) {
self.image = nil
// checks cache
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
//download
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//error handling
if let error = error {
print(error)
return
}
DispatchQueue.main.async(execute: {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as NSString)
self.image = downloadedImage
}
})
}).resume()
}
我认为解决之道在于重装的CollectionView我只是不知道到底哪里做它的地方。
有什么建议吗?编辑: 这里是函数被调用的地方;我cellForItem at indexpath
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userResultCellId, for: indexPath) as! FriendCell
let user = users[indexPath.row]
cell.nameLabel.text = user.name
if let profileImageUrl = user.profileImageUrl {
cell.profileImage.loadImageUsingCacheWithUrlString(profileImageUrl)
}
return cell
}
其他唯一的,我相信可能会影响图像装载的是这个功能我用它来下载用户数据,这就是所谓的viewDidLoad
,但是其他所有的数据下载正确。
func fetchUser(){
Database.database().reference().child("users").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.setValuesForKeys(dictionary)
self.users.append(user)
print(self.users.count)
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
})
}
}, withCancel: nil)
}
当前的行为:
至于当前行为的最后一个单元是显示下载的轮廓影像的唯一细胞;如果有5个单元格,第5个是唯一一个显示配置文件图像的单元格。另外当我更新数据库,即注册一个新用户时,collectionview会更新并正确显示新注册用户的个人资料图像,以及正确下载图像的最后一个单元格。然而,其余的,没有配置文件图像。
你可以显示你的CollectionViewController吗? – javimuu
@javimuu我包括函数被调用的地方。 – Stefan
使用sdwebimage库轻松加载图像。 –