iOS Concurrency with GCD & Operations

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

Part 3: Operations & OperationQueues

21. Challenge: Implement a Dependency

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: 20. Dependencies Next episode: 22. Cancel Operations

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.

Transcript: 21. Challenge: Implement a Dependency

Challenge: Implement Dependency

Continue with your final project from the previous video or open the starter project. Update downloadImageOp in ImageStore to apply the tilt-shift filter to the downloaded image.

  • Hint 1: Create downloadOp and tiltShiftOp operations, and add a dependency to tiltShiftOp
  • Hint 2: Set the completion block on tiltShiftOp
  • Hint 3: Add both operations to the operation queue

Pause this video while you complete this challenge, then resume playing the video to see my solution.

Replace the line in downloadImageOp where you set and declare operation with the following code:

let downloadOp = NetworkImageOperation(url: images[index].url)
let tiltShiftOp = TiltShiftOperation()
tiltShiftOp.addDependency(downloadOp)

Instead of having a single operation, you now have two operations and a dependency between them. All the errors are because there’s no operation anymore, but you’ll fix that right away. Change the completion block to use tiltShiftOp instead of operation:

tiltShiftOp.completionBlock = {  // change operation to tiltShiftOp
  guard let image = tiltShiftOp.image else { return }  // change operation to tiltShiftOp
  DispatchQueue.main.async {
    self.images[index].image = image
  }
}

Instead of setting completionBlock on operation, you set it on tiltShiftOp, because it will provide the final image. Note that you dispatch to the main queue because you’re modifying a published value, which ContentView displays. Instead of adding operation to the queue, add your new operations:

queue.addOperation(downloadOp)
queue.addOperation(tiltShiftOp)

You need to add both operations to the queue. The queue will keep track of dependencies and only start the tilt-shift operation once the download is complete. Build and run to scroll through your tilt-shifted images.

Well done! Ah, but there’s still the problem of downloading and filtering images even when they scroll offscreen. In the next video, you’ll finally implement canceling operations when their image scrolls offscreen.