Я пытался создать фотогалерею в 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
}
}
}
}
Я ценю вашу помощь. Спасибо.