我有一個照片瀏覽應用程序。我正在使用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下載任務節省互聯網帶寬。