Closure for async call handling

Mohit Kumar
3 min readJul 27, 2018

--

This tutorial will focus on that how closure is helpful for handling async calls in iOS. Async calls may take few seconds before responds so we require some event callback once the response is available. We can use closure for this purpose.

In this tutorial we will:

  1. Write HttpClient class for handling REST api call and will make REST async call from UIViewController.
  2. Parse JSON response to Model using native Decodable protocol.
  3. Serve response to ViewController class where data will be displayed in UITableView.

So lets start one by one through each steps. First of all we need to write HTTPClient class with REST api method. This method will be able to handle GET and POST calls.

First let define enum for API call type in HTTPClient class:

We need to keep HTTPClient as singleton as we don’t require multiple object for this class:

Now write function for async call as given below:

Above method takes following parameters:

  1. url: URL string to be passed.
  2. json: In case of POST call you can pass JSON body.
  3. apiType: Weather using GET or POST api.
  4. success closure
  5. failure closure

In the function body first of all we need to create NSMutableRequest object as given below:

To handle POST api call we can add below check after request is created:

In above code we did following tasks:

  1. Set content type if it is a POST call.
  2. Check if body is valid and if body is not valid then we call onFailure() as we are having body but the body is not convertible to JSON.
  3. If body is valid JSON then we set it to http request body.

Now once all is set then we can create NSURLSession object and can call for API as given below:

In above code snippet we are making onSuccess() callback using closure when we received success response. If any error then we are calling onFailure().

Now lets go to ViewController class and lets consume http function. For this example we will be using https://jsonplaceholder.typicode.com/posts api which return some dummy POST data in following format:

In ViewController class we make call in following manner:

In above code, if app receive success response then we can Parse JSON and display in UITableView. In case of failure we can made handling as required by app.

Now lets come to JSON parsing part. In Swift 4 Apple introduced Encoding and Decoding protocol ( for more details please refer here ). I am not going to discuss them in this tutorial so please refer then from link given .

So lets create Post Model class as given below:

Please note that we keep Model format same As JSON given above. The only difference is that we are using postId instead of id key in JSON. Swift provide easy for for these kind of custom mapping. You can define Coding keys enum and can map all custom keys as per your convenience.

Now go to ViewController and decode object from API as given below:

You can see how simple is it now to parse JSON without using JSONSerialization. we write [Post].self because we are having array of Posts. In case of single object you just require to write Post.self.

Now data is available in is class variable so you can display the same in you UI OR UITableView as you want.

In my git project, I have parsed one more complex structure just to make more clarity about Codable protocol. On tap of UITableViewCell, I redirect to second page where we made call for user data which have complex JSON structure as given below:

For above complex JSON you I did write my model class as given below:

I hope you can now easily debug above schema.

You can found complete git project here:

--

--