Reputation: 197
I have tried using NSURLConnection inside NSThread and dispatch_queue. The implemented NSURLConnectionDelegate methods are not called. But when I used NSOperation inside of NSThread and NSOperationQueue, the methods are called.
Upvotes: 0
Views: 1379
Reputation: 6590
You could use the block-based approach:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
// we should check that data is OK
NSLog(@"Data received");
}
}
Upvotes: 0
Reputation: 9185
The NSURLConnectionDelegate
methods aren't being called because your thread or dispatch block completes execution before the delegate methods can be called. If you want to use NSURLConnection
in its own thread in this way, as others have suggested you must keep the run loop going.
Here is an example. Basically
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
finished = TRUE;
}
All of the above said, would it not be better to use the NSURLConnection
synchronous API inside of your asynchronous block? For example, you could wrap your synchronous request inside an NSOperation
Upvotes: 3