I am using GCD to send HTTP request asynchronously. Here is the code that doesn’t work:
dispatch_async(connectionQueue, ^{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];//Not working
});
the above code is not working at all. I am not getting any call back in NSURLConnectionDelegate’s methods.
But when i tried the following code, everything worked fine and i got proper callbacks
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:someURL]]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
dispatch_async(connectionQueue, ^{
[connection start]; // working fine. But WHY ????
});
Can some one please explain this weird behavior of block/GCD?
Try this in the first part of your code sample-
If you put the connection in a background queue, it gets shoved away after the queue is complete, and thus you don’t get your delegate callbacks. The connection can be in the main queue so it stays in the main run loop for callbacks to occur. Or, you can create your own runloop that handles your background operation for you as suggested by others.