Using data semphores in iOS (Synchronous Request)

Introduction

As per Apple Documentation,

A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made.

I am just providing an example here so that you can take a look how it works.

Its not recommended to use the data_semaphore in your application as it has some lay offs in term of performance. Its always recommended to use the NSOperationQueue and NSOperation to get these things done. **Only use this approach when its the only option available.

import UIKit
import Foundation

let url:NSURL = NSURL(string: "http://jsonplaceholder.typicode.com/posts")!;
let urlRequest:NSURLRequest = NSURLRequest(URL: url);

var session:NSURLSession = NSURLSession.sharedSession();

//Create a semaphore
var dataSemaphore = dispatch_semaphore_create(0);

var responseData:NSURLResponse?;

var dataObject:NSMutableArray?;

//By default datatask is asynchronous, making use of data semaphore to make the request synchronous.

session.dataTaskWithRequest(urlRequest, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in

dataObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSMutableArray;

println(dataObject!);
responseData = response;

dispatch_semaphore_signal(dataSemaphore);

}).resume();

dispatch_semaphore_wait(dataSemaphore, DISPATCH_TIME_FOREVER);

//This print statement is executed once the above task is completed.

println("test");

 

As you run the application in your Xcode playground, you will come to notice that the last is printed after the request is completed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s