In Multitasking environment developers like you, We always give best to the application so, End user interaction will be smooth. But making application user interactive it’s not an easy task in a multithreaded environment, because the user can do different tasks at a time. So today I will discuss how to make multiple asynchronous tasks to synchronously way in swift using GCD(Grand Central Dispatch).

GCD is a core level powerful tool to handle multithreading in the application. For more details, you can check apple documentation regarding gcd. So let’s start with one Example, I have a situation where we need to request two different asynchronous API(Web Service) at a time and handle the response.

We will do this exercise in Xcode PlayGround, So open Xcode Go to File -> New -> Playground, Select Blank playground and then Next and give the name as HTTPRequest, it will save it as HTTPRequest.playground in your specified directory.

First, we will create HTTPRequest handler class, the main purpose of this class is it will request to the web server and get a response from the web server, here we just handling only GET request for this example purpose, you can try with POST, DELETE and PUT as well.

class HTTPRequest: NSObject {

   // GET Service

   func onHandlelGETService(_ urlString: String,_ completion: @escaping (Data?, URLResponse?, Error?) -> ()) {

       let url = URL(string: urlString)

       let session = URLSession.shared

       session.dataTask(with: url!) { (data, response, error) in

           if let errorResponse = error {

               completion(nil, nil, errorResponse)

           }

           else {

               if let httpResponse = response as? HTTPURLResponse {

                   if httpResponse.statusCode != 200 {

                       let errorResponse = NSError(domain: "com.error", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey :"Http status code has unexpected value"])

                       completion(nil, nil, errorResponse)

                   }

                   else {

                       completion(data, response, nil)

                   }

               }

           }

       }.resume()

   }

}

Above, the code is straightforward, we have created HTTPRequest class and create function onHandleGETService which takes the argument of string URL and it will request get http request using URLSession Data task and give a callback to method caller.

let httpResonce = HTTPRequest()

// First we create DispatchGroup() instance

let serialGroup = DispatchGroup()

// The ‘enter’ method add the task in the dispatch  group

serialGroup.enter()

httpResonce.callGETService("http://www.google.com") { (data, response, error) in

   if error != nil {

       print("First Request got completed with error.....")

   }

   else {

       print("First Request got completed.....")

 

   }

   // The ‘leave’ method remove task from dispatch group

   serialGroup.leave()

}

serialGroup.enter()

httpResonce.callGETService("http://www.yahoo.com") { (data, response, error) in

   if error != nil {

       print("Second Request got completed with error.....")

   }

   else {

       print("Second Request got completed.....")

   }

   serialGroup.leave()

}

// The ‘notify’ method will execute when all task is finished.

serialGroup.notify(queue: DispatchQueue.main) {

   print("All Groups request completed.....")

}

In the above code, we have used DispatchGroup() to fulfill our requirements. So let’s dig into that, first, we have to create an instance of the DispatchGroup and here it’s magic happen.

Before the call of each GET request, we have to use ‘enter’, it will tell GCD that task is added in the queue.

After each callback block, we have use ‘leave’, it will tell GCD that task is completed and you can remove that task from the queue.

Here we need to make sure we have to call function ‘enter()’ and ‘leave()’ for each task, otherwise group never gone be finished.

Next, ‘notify()’ method will execute when all the task got finished, which we have called in ‘main’ queue.

To know more about our achievements in detail, please click here or contact us

Related Posts

What are Citizen Developers and How They Help Scale

Citizen developers play a vital role in helping you scale the your RPA strategy and achieve digital transformation.

Let’s talk!
We’d love to hear what you are working on. Drop us a note here andwe’ll get back to you within 24 hours