I've been trying to create a photo gallery in Swift 3.0 and I want to load images stored in the document directory into the collection view asynchronously. I tried DispatchQueue.main.async
but it blocks the main thread and freezes the app for a few seconds:
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
}
And the ImageCell class:
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
}
}
}
}
I appreciate your help. Thank you.