Chapter 7
Handling Asynchronicity with Closures

Our player UI can play and pause audio, update the button label based on whether audio is playing or paused, and show a title. And in the last chapter, we exposed that functionality to unit testing, to make sure it keeps working. But there’s one part of the UI we still haven’t implemented: the label that shows the current playback time.

Thing is, time can be a real challenge for software. It’s easy to write a series of instructions and have them executed in order. It’s harder when things naturally happen at unpredictable times that we have to respond to, or when we want something to happen in the future, or if we have to respond to something and then do something.

We’ve seen two of iOS’s older approaches to this: Timers to do work in the future (possibly repeatedly), and key-value observing (KVO) to respond to changes in supported properties. But both require somewhat clunky schemes to call back to designated objects, with special conventions for method names or parameter lists. It would be nice if there were something cleaner, so we could just say, “Every half-second, do this,” or “When something special happens, do that.”

Lucky for us, this cleaner approach—a Swift type that itself contains executable code—already exists, and we’re going to put it to work in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset