12/08/2018, 14:10

Newbies’ Guide To iOS Callbacks

Unlike my other posts, this time I’m writing a tutorial for the beginners. As you can tell from the title, this time it’s about iOS, more specifically its callbacks. Since this post is aimed for the newcomers in iOS (or any mobile platform) development, I think it’s necessary to ...

Unlike my other posts, this time I’m writing a tutorial for the beginners. As you can tell from the title, this time it’s about iOS, more specifically its callbacks.

Since this post is aimed for the newcomers in iOS (or any mobile platform) development, I think it’s necessary to discuss a few things in some detail before coming to our main topic.

In application development, there comes situation like one class calling a method of some another class to do something. Upon completing that task in the called method, the caller class decides what to do next. In this kind of scenario the caller class needs to know exactly when the called method finishes its job or maybe the caller class must need some data to execute the next lines of codes, but the data must be served from the called method after it gets the job done.

So, what’s the big deal here? Upon returning from a method, the caller always gets its data. There’s nothing to worry about here. Or is it? Let’s find out.

In case of multithreading, where it is a good practice to hand the memory and time-intensive tasks over other threads, or in case you like to do something in the background while leaving the UI thread free to user interaction and do other business in the meantime, you must make sure that the UI thread (or any other thread you like) knows when the background tasks are finished so that you can update the UI as per the data you get from the background. In this case, you need to come to an agreement with the method that performs background task to make sure it delivers you the data you need when it finishes its job. To do this, you have to create a medium of communication between classes, and here come callbacks to lend you the helping hand.

Let’s imagine a scenario where you want to click a button, say ‘OK’ button of an alert dialog. This click is an event that you want the system to know about. Just think of it as a ‘call’ to the system. When the system gets to know about this, it calls you back with some necessary information needed to perform a task, say dismiss the view controller. You need a method/function for this to accomplish which may take one or more parameters (or no parameters at all) to serve the necessary information to you. This is called the callback method/function/block and in iOS’ terms, takes the form of a closure. Inside that block you write your code to perform the desired actions.

This is the most basic idea of callbacks. There’s no better way to explain this than writing some code to create an app that relies on some sort of communication between two of its classes. We’ll come to that very soon, but, before that, let’s see how many ways there are to accomplish the task of back-and-forth communication. For the simplicity of our example, our app will demonstrate the following techniques to show you the basics.

  1. The delegation pattern: if you ever played with Android, then this pattern should be familiar to you. It’s exactly like implementing an interface in a class and setting the listener of your objects with the implementation of that interface. In iOS, the term ‘interface’ is replaceable with ‘protocol’ and ‘listener’ with ‘delegate’. It may sound a bit messy and scary at this moment, but I’ll explain all these through the example app.
  2. The observer pattern: it is basically a publisher-subscriber (pub-sub) pattern. There can be multiple classes subscribing to a class, just like we tune our radios to a specific station. When the class publishes something, like the station broadcasts, the subscriber classes get to know about it. This pattern is useful in cases where multiple classes depend on one class to perform something.
  3. Callbacks using Closure: this is like magic. Closure is just a function without a name. It can have its own parameters and return statement, and can be passed as an argument to another method. It is easier to write (and read) than implementing the delegation or observer pattern. This is suitable for one-to-one communication between classes.

Enough talking, let’s do some real business to make everything clear.

In our example app, there are two view controllers. In the first one, user has to provide the values of two operands and choose one operation from summation, multiplication and concatenation. User can also select the datatype of those operands. Clicking the button denoting the operation type, user can go to the second view controller where he/she can see the result along with the numbers of each data type the operations have been performed on. Upon going back to the first view controller, user can see the updated number of each operations performed. To update the numbers of operations in the first view controller, I’ve used the three patterns stated above, each manipulated using their respective buttons. Have a look below to get an idea of what the app looks like.

alt

alt

alt

Before diving deeper into the codes, I would recommend to download the project from GitHub and build in your Xcode. It’s written in Swift 2.0 and my Xcode version is 7.3.1. This will save a lot of time for both you and me from building the entire app from the scratch and me telling you every step down the way. And don’t forget to run the app on simulator. Also keep in mind that I won’t explain the whole project line by line since it will be very tiresome not only for you, but also for me. So, I’ll skip a lot of details to make this post as compact as possible to make sure we’re not deviating from the main topic which is to show you how to communicate with other classes and how easy it can get using callbacks.

The project starts with creating the storyboard. As you can see from the downloaded project, there’s Main.storyboard containing two scene’s for the two screens of our app. Likewise, there are HomeViewController.swift and ResultViewController.swift for the 1st and 2nd scenes respectively to handle all the user interactions and logics.

In the first scene, there are three buttons on the top to choose the data type. Below that, two TextFields along with a Label for each to get the input of X and Y values. At the bottom, there are three more buttons to select the operations. After selecting the data type and providing the inputs, user can click one of the buttons at the bottom to see the result in the next screen. To prevent user from making blunders, we want to disable the ‘Concat’ button if ‘Int’ or ‘Float’ buttons are clicked.

Similarly clicking the ‘String’ button will disable the ‘Sum’ and ‘Mul’ buttons. Upon returning from the second screen the three Labels at the bottom will bIn the first scene, there are three buttons on the top to choose the data type. Below that, two TextFields along with a Label for each to get the input of X and Y values. At the bottom, there are three more buttons to select the operations. After selecting the data type and providing the inputs, user can click one of the buttons at the bottom to see the result in the next screen. To prevent user from making blunders, we want to disable the ‘Concat’ button if ‘Int’ or ‘Float’ buttons are clicked. The three Labels below them will be updated with the number of operations. I’m going to leave the codes to you to understand it by yourself (if you wish             </div>
            
            <div class=

0