0

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.

samvijay
  • 197
  • 5
  • 14
  • Does your thread execute a runloop? – Christian Stieber Aug 28 '12 at 10:11
  • no. i just created a thread and call [thread start] to execute. The url connection is scheduled in currentRunLoop with NSRunLoopCommonModes. Will i need to create a run loop for the thread i have created?(i am just a beginner in Objective-C and iOS programming). – samvijay Aug 28 '12 at 10:29

2 Answers2

3

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

FluffulousChimp
  • 9,157
  • 3
  • 35
  • 42
  • I am looking for a solution like this only. Thanks a lot. It works now. I don't want to use NSURLConnection synchronous APIs since I need details of the downloading data (like file name, size, etc.,) which i could get in Asynchronous APIs. – samvijay Aug 28 '12 at 17:12
0

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");
        }
    }
Resh32
  • 6,500
  • 3
  • 32
  • 40