[英]DispatchQueue.main.async blocking the main thread
我一直在嘗試在 Swift 3.0 中創建一個照片庫,我想將存儲在文檔目錄中的圖像異步加載到集合視圖中。 我嘗試了DispatchQueue.main.async
但它阻塞了主線程並凍結了應用程序幾秒鍾:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = "ImageCell"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ImageCell
let url = self.imageURL[indexPath.row]
cell.lazyLoadImage(from: url)
return cell
}
和 ImageCell 類:
class ImageCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
func lazyLoadImage(from url: URL) {
DispatchQueue.main.async {
if let image = UIImage(contentsOfFile: url.path) {
self.imageView.image = image
}
}
}
}
我感謝您的幫助。 謝謝你。
首先切換到后台線程並在其上加載圖像,然后再次切換到主線程並顯示圖像。
func lazyLoadImage(from url: URL) {
DispatchQueue.global(qos: .userInteractive).async {
if let image = UIImage(contentsOfFile: url.path) {
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
}
你做錯了。 簡而言之,我可以說這不是“延遲加載”。 您正在做的是阻止線程從URL
下載內容並將其加載到UIImageView
。 在下載發生並且您在“可重用單元”中使用它之前,線程不會被釋放,很明顯您的應用程序會卡住!
解決方案
有許多最流行的庫,如AlamofireImage 、 SDWebImage 、 Kingfisher 。 我從中選擇“SDWebImage”,您可以通過以下代碼以async
方式調用加載圖像:
imageView.sd_setImage(with: url , placeholderImage: nil)
另外,請參閱此 SO 問題( 如何使用 swift 在表視圖中實現延遲加載圖像)以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.