1

I am trying to insert images into collectionView asynchronously because images make rendering slow. This code can insert images but some images are displayed twice. How can I set images in right place of collectionView?

class fooCollectionViewCell {
   imageView.loadImageAsynchronously(url: "https://~")
}

extension UIImageView {
    func loadImageAsynchronously(url: URL?) -> Void {

        if url == nil {
            self.image = UIImage(named: "no_image")
            return
        }

        DispatchQueue.global().async {
            do {
                let imageData: Data? = try Data(contentsOf: url!)
                DispatchQueue.main.async {
                    if let data = imageData {
                        self.image = UIImage(data: data)
                    } else {
                        self.image = UIImage(named: "no_image")
                    }
                }
            } catch {
                DispatchQueue.main.async {
                    self.image = UIImage(named: "no_image")
                }
            }
        }
    }
}
Ken
  • 109
  • 9
  • 1
    For asynchronous URL loading, you should use a Data Task (https://developer.apple.com/documentation/foundation/url_loading_system) – Clashsoft Mar 01 '19 at 17:24
  • The initializer `init(contentsOf:)` should only be used for loading data from a __local__ URL, never a remote one, since it is a synchronous function (due to the fact that its an initializer). You need to use `URLSession.dataTask` for downloading images asynchronously. – Dávid Pásztor Mar 01 '19 at 17:30

0 Answers0