0

I want to do a web service call on a separate thread. I am using the below code,

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // My web service request goes from here 
});

The request goes successfully, however there is no response coming back, I am not able to figure out why.

If I use

dispatch_async(dispatch_get_main_queue(), ^{
    // My Web service request goes from here 
});

Response is coming back but UI is blocked till then, I want to do the web service request in a separate thread without blocking the UI.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Harish
  • 252
  • 1
  • 13
  • Is there a particular reason you are not using `NSURLConnection`'s `+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler`? That would take care of sending the request on a background thread, and then you could do what you need in the `completionHandler`. Or better yet, you could use `AFNetworking`. – Andrew Monshizadeh May 25 '14 at 18:46

1 Answers1

0

The idea is to use a background thread for the request, but handle the result (which changes UI) on the main. This answer shows how (basically by nesting your main queue block inside your background block), but there's a simpler way provided by NSURLConnection:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http..."]];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    // update the UI here
}];

This handy method performs the request off the main, and -- since you pass it the main queue -- performs the completion block on the main.

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
  • I understand, however my question is why is that if i run from a globalqueue or detach new thread my response is not coming back. – Harish May 26 '14 at 07:11