how to setup a operation queue that downloads images asynchronously in swift

To setup an operation queue that downloads images asynchronously in Swift, follow these steps:

  1. Create an OperationQueue instance:

    main.swift
    let operationQueue = OperationQueue()
    
    38 chars
    2 lines
  2. Create a new Operation subclass that will be responsible for downloading images. In the main method of this subclass, fetch image data asynchronously and store it in a property:

    main.swift
    class ImageOperation: Operation {
        
        var imageUrl: URL
        var imageData: Data?
        
        init(imageUrl: URL) {
            self.imageUrl = imageUrl
            super.init()
        }
        
        override func main() {
            let task = URLSession.shared.dataTask(with: imageUrl) { (data, response, error) in
                guard let data = data else { return }
                self.imageData = data
                self.isFinished = true
            }
            task.resume()
        }
    }
    
    459 chars
    20 lines
  3. Create an instance of ImageOperation for each image you want to download, passing in the URL of the image:

    main.swift
    let imageUrls: [URL] = [url1, url2, url3]
    var operations: [ImageOperation] = []
    
    for imageUrl in imageUrls {
        let operation = ImageOperation(imageUrl: imageUrl)
        operations.append(operation)
    }
    
    199 chars
    8 lines
  4. Add all of the ImageOperation instances to the operation queue:

    main.swift
    operationQueue.addOperations(operations, waitUntilFinished: false)
    
    67 chars
    2 lines
  5. When the image downloads are complete, use the imageData property of each ImageOperation instance to create UIImage objects:

    main.swift
    for operation in operations {
        guard let imageData = operation.imageData else { continue }
        let image = UIImage(data: imageData)
        // Do something with the image...
    }
    
    175 chars
    6 lines

Note: If you need to display the images in a UI component, make sure to update the UI on the main thread.

gistlibby LogSnag