我有一个照片浏览应用程序。我正在使用UICollectionView来显示照片列表。通过下载网站的HTML源代码从我的网站提取照片并获取照片URL。对于UICollectionView中的每个单元格,我必须从不同的URL下载HTML源代码并从中提取照片。这是我的cellForItem功能:iOS Swift UICollectionView照片浏览 - 如何停止取消DispatchQueue单元格不可见时
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "siteAlbumCellID", for: indexPath) as! AlbumCell
...
getListPhotoURLs(album: album, updateSite: updateSite, handler: { [weak self] (photos) in
guard let ss = self else { return }
if let photos = photos{
if photos.count > 0{
...
}
}else{
cell.aiView.stopAnimating()
cell.ivPhoto.image = #imageLiteral(resourceName: "cover")
}
})
...
}
我只让网页要由HTML烃源下载后使用缓存下载一次。 和这里的getListPhotoURLs功能:
func getHTMLSource(url: String, cookie: String? = nil, handler: @escaping (_ result:String?) -> Void){
DispatchQueue.global().async {
guard let myURL = URL(string: url) else {
print("Error: \(url) doesn't seem to be a valid URL")
DispatchQueue.main.async {
handler(nil)
}
return
}
do {
var myHTMLString = try String(contentsOf: myURL, encoding: .utf8)
DispatchQueue.main.async {
handler(myHTMLString)
}
} catch let error {
print("Error: \(error)")
DispatchQueue.main.async {
handler(nil)
}
}
}
}
当滚动视图到达底部时,应用程序会从服务器加载更多的数据,这里是哪里出了问题就出现了:当我向下滚动到下一路,应用程序仍然是下载所有单元格的所有HTML源代码,我必须等待一段时间才能加载下一页数据。这是因为许多HTML下载任务正在运行,并使用大量的互联网带宽
我希望当用户滚动收集视图,那些未完成的HTML下载任务需要停止不可见的单元格的getHTMLSource函数时,为可见单元的其他html下载任务节省互联网带宽。