Concurrency in iOS: serial and concurrent queues in Grand Central Dispatch (GCD) with Swift 4

Today, I’ll show you how to use Swift 4 and the Grand Central Dispatch (GCD) application programming interface (API) to implement the execution of (multiple) tasks in the background, i.e., parallel/concurrent execution of tasks on a multicore CPU. I’ve built a sample app that gives you two options: 1) synchronous execution of tasks in the background and 2) asynchronous execution of tasks in the background. All my Swift 4 code from this article, part of an Xcode 9 project which builds a fully-functional working sample app, is available for download here. Join me in: reviewing concurrent programming concepts; reviewing my concurrent Swift 4 code; and, examining videos of my app in action, videos of console output from my app, and the console output text itself. I’ll even show you how to graphically visualize my app’s CPU and thread usage with Xcode’s Debug Navigator.

This is a look at the app — a snapshot — after all images have finished downloading asynchronously in the background:

Here’s a video of the app downloading images asynchronously in the background:

Press the play button if you missed the first showing

Continue reading “Concurrency in iOS: serial and concurrent queues in Grand Central Dispatch (GCD) with Swift 4”

Concurrency in iOS: Introduction to the abstract Operation class and using its BlockOperation subclass to run tasks in parallel

[Download the full Xcode 9 project, written in Swift 4, from GitHub.]

Swift tutorials by iosbrain.comI’m going to introduce you to iOS concurrency with simple Swift 4 code that uses an API based on the Operation abstract class. In more complex scenarios, you would subclass and customize Operation, but iOS provides the built-in BlockOperation subclass of Operation which we’ll use here. I’ll review the tenets of concurrency, emphasize why it is necessary in almost all apps, explain the basic infrastructure of Operation, compare it to Grand Central Dispatch (GCD), and then walk you through the Swift 4 code I wrote to implement concurrency in a real-live app based on BlockOperation. I’ll even show you how to graphically visualize your app’s CPU and thread usage with Xcode’s Debug Navigator. Here’s the app that we’ll build together:

Press the play button if you missed the first showing

We now live in the day and age of writing apps that can run on devices with CPUs that have multiple cores. We can go way beyond the notion of “multitasking” as a bunch of processes vying for a “timeslice” of the CPU. We can literally run processes simultaneously on different cores. As iOS developers, it is vitally important that we understand the concept of concurrency. Why?

Continue reading “Concurrency in iOS: Introduction to the abstract Operation class and using its BlockOperation subclass to run tasks in parallel”