这是代码。这是我的UICollectionViewDataSource
课程。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = "UICollectionViewCell"
let photo = photos[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! PhotoCollectionViewCell
let url = ImageUploaderAPI.urlForPhotoPath(photoTitle: photo.remoteURL)
if (photo.image == nil) {
Alamofire.download(url).downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
photo.image = image!
cell.updateWithImage(image: image)
print("Downloaded: " + url.absoluteString)
collectionView.reloadData()
}
}
} else {
cell.updateWithImage(image: photo.image)
}
return cell
}
progress.fractionCompleted
显示正在下载图像,但我不确定为什么没有图像正在更新。是因为Alamofire如何异步工作?任何建议将不胜感激。
答案 0 :(得分:1)
以下是3种可能的解决方案。第一个是因为后台线程问题。而不仅仅是collectionView.reloadData,请尝试使用:
DispatchQueue.main.async {
collectionView.reloadData
}
另一个可能的解决方案是.resume问题?您可能想尝试添加.resume,如下例所示:
if (photo.image == nil) {
Alamofire.download(url).downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
photo.image = image!
cell.updateWithImage(image: image)
print("Downloaded: " + url.absoluteString)
collectionView.reloadData()
}
}.resume
} else {
cell.updateWithImage(image: photo.image)
}
return cell
}
我的第三个也是最后一个解决方案是简单地摆脱if (photo.image == nil) {
希望这有帮助
答案 1 :(得分:1)
我最终这样做了:
cell.activityIndicator.startAnimating()
if (photo.image == nil) {
let dataTask = URLSession.shared.dataTask(with: url) {
data, response, error in
if error == nil {
if let data = data {
let image = UIImage(data: data)
print("Downloaded: " + url.absoluteString)
DispatchQueue.main.async {
photo.image = image!
collectionView.reloadItems(at: [indexPath])
}
}
} else {
print(error)
}
}
dataTask.resume()
} else {
cell.updateWithImage(image: photo.image)
}
cell.activityIndicator.stopAnimating()
cell.activityIndicator.isHidden = true
return cell