Leave a rating/review
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
downloadOpandtiltShiftOpoperations, and add a dependency totiltShiftOp -
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.