iOS Concurrency with GCD & Operations

Sep 12 2023 · Swift 5.8, macOS 13, iOS 16, Xcode 14.3

Part 3: Operations & OperationQueues

19. Challenge: Download Images in OperationQueue

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 18. Asynchronous Operations Next episode: 20. Dependencies

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Challenge: Download Images in OperationQueue

The playground in the starter folder has part of the ImageLoadOperation and the same image url components you used in the dispatch group challenge in Part 1. The first part of your challenge is to fill in the operation’s main function, to download an image from the input url. The second part of your challenge is to use instances of this operation in an OperationQueue to download all the images.

open class AsyncOperation: Operation {
  ...
}
class ImageLoadOperation: AsyncOperation {
  private let url: URL
  var image: UIImage?

  init(url: URL) {
    self.url = url
    super.init()
  }
  
  // TODO: Call dataTask with url and save image
  override func main() {
    
  }
}
URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
  guard let self else { return }

}.resume()
defer { self.state = .finished }
guard error == nil, let data else { return }
image = UIImage(data: data)
let base = "https://cdn.kodeco.com/books/con/image-from-rawpixel-id-"
let ids = [466881, 466910, 466925, 466931, 466978, 467028, 467032, 467042, 467052]
var images: [UIImage] = []
let queue = OperationQueue()
for id in ids {
  guard let url = URL(string: "\(base)\(id)-jpeg.jpg") else { continue }

}
let op = ImageLoadOperation(url: url)
op.completionBlock = {
  if let image = op.image { images.append(image) }
}
queue.addOperation(op)
3.188688039779663 (or ~1.284000039100647 or 2.58...)
w 600 h 516