iOS 10 Xcode 8 Swift 3.0 Multithreading GCD Grand Central Dispatch Tutorial

iOS Dev. #2 – Grand Central Dispatch Multithreading Tutorial, Stack Views & Image Fetching Swift 3.0

Full Code: Multithreading Tutorial

Swift 3.0 Multithreading & Grand Central Dispatch

In the second tutorial on iOS development, we are looking at Grand Central Dispatch or GCD. This particular framework allows you to create multiple threads which will run in series or parallel. If you are not yet familiar with what a thread is, we will cover it in this tutorial. We will also discuss why it is important in software development and iOS in particular.

Multithreading

A thread is simply a block of the program. Multithreading is a software concept which allows you to schedule your threads, or blocks of your programs, to run simultaneously. In reality, they aren’t exactly ran at the same time, but are rather interlaced like threads. This gives the user access to the UI while you perform other operations in the background.

iOS relies on multithreading heavily as you often need to retrieve or save data. These operations are often CPU intensive and cause the application to stall if it’s not implemented on the proper thread. To prevent your application from “hanging” while the user is browsing through it, you must utilize multithreading. Keep in mind that Apple has done a great job at making it extremely easy for you to do this with their Grand Central Dispatch. You have no excuse!

Hardware & Software for the Project

We will be using Xcode 8.0 for this tutorial. Swift 3.0

UIViewController Implementation

For demonstration purposes, I’ve created a UIViewController with an image, 3 buttons, a slider and an activity indicator. The final result looks as follows:
UIViewController Multithreading Tutorials Swift 3.0

Implementing the Button IBActions & Image IBOutlet

After building the UIViewController, we obviously need to create IBActions and IBOutlets to the appropriate elements. In this case, we have 3 buttons, 1 image view and an activity indicator. Their outlets will be as follows:
@IBOutlet weak var myImage: UIImageView!
@IBAction func button1Pressed(_ sender: UIButton) {
updateImage(button: 1)
}
@IBAction func button2Pressed(_ sender: UIButton) {
updateImage(button: 2)
}
@IBAction func button3Pressed(_ sender: UIButton) {
updateImage(button: 3)
}
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

Note that inside of the IBAction statements for the buttons, I am calling a function which will be implemented below. At this point, all you need to know is that it is recognizing which button has called it through the identifiers above.

Updating the image asynchronously

We will be utilizing the Grand Central Dispatch or GDC in order to update the image in our view asynchronously. the following function is implemented in the UIViewController:
func updateImage(button: Int) {
self.activityIndicator.startAnimating()
var imageURL = URL(string: "")
switch button {
case 1:
imageURL = URL(string: "http://www.spyderonlines.com/images/wallpapers/electronic-backgrounds/electronic-backgrounds-23.jpg")
case 2:
imageURL = URL(string:"https://upload.wikimedia.org/wikipedia/commons/d/d9/Arduino_ftdi_chip-1.jpg")
case 3:
imageURL = URL(string:"https://www.walldevil.com/wallpapers/w03/871688-circuits-computer-technology-electronics-pcb.jpg")
default:
break
}
// Asynchronous
DispatchQueue.global(qos: DispatchQoS.userInitiated.qosClass).async {
let fetch = NSData(contentsOf: imageURL! as URL)
DispatchQueue.main.async {
if let imageData = fetch {
self.activityIndicator.stopAnimating()
self.myImage.image = UIImage(data: imageData as Data)
}
}
}
}

The function is straight forward. First, we will start the activity indicator and determine which button was pressed. This is done through the “button” variable. A switch statement is used to assign the appropriate URL. Note that I’m using random images from the web for learning purposes.

The “//Asynchronous” mark is what delimits our multithreading instructions. Through the DispatchQueue command, we are dispatching an asynchronous instruction of type “UserInitiated”. If you’re curious as to what other types of general purpose threads there are, I would recommend referring to the documentation. Here’s a link: Apple DispatchQueue documentation. Note that after the image retrieval, we are dispatching yet another thread, but this time on the main queue. This is due to the fact that you should ONLY update your UI on the main thread. The instruction stops the activity indicator and assigns the new image to our UIImage outlet.

UIViewController Final Outcome

If you’ve followed all of the instructions outlined here and the video, you should have an “asynchronous” UIViewController implementation. It is capable of retrieving images from the web while the user can still work with the UI.

Video Tutorial of the build:

Conclusion

Multithreading is extremely powerful. It is used in many languages and is particularly important in iOS development. We’ve only scratched the surface of it’s capabilities in this tutorial. However, the demonstrated functionality will be used in 95% of all the applications.

Thank you for reading & watching,
– Vlad Romanov, EEEnthusiast

Leave a Reply

Your email address will not be published.

CommentLuv badge