Wait for HTTP request to finish in objective c for iOS

Facebook provides a asynchronous, non-blocking API for handling HTTP requests. We wanted to be able to wait for the HTTP request to return with the result. Specifically, we are posing an event to Facebook and we want to know the FacebookEventID of the event that we just posted.

In order to do that, we created a variable “postRequestReturned” and set it to false. In the post function, we send the request and then block the thread as long as “postRequestRetured” is false. A point to note here is that a simple while loop resulted in blocking the Main thread and making the application unable to receive the response from Facebook. Instead, we used the Runloop libraries in objective c,

Runloop is a loop your thread enters and uses to run event handlers in response to incoming events. Some good documentations

http://stackoverflow.com/questions/3615939/wait-for-code-to-finish-execution

https://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html

The code snippet that we used


while(!postRequestReturned){

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

}

In the completion handler for the Facebook request, we set the postRequestReturned variable to true.

Advertisements
This entry was posted in IPhone App Development and tagged , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s