views:

72

answers:

2

Hi,

The connection doesn't respond when beeing set from a new thread:

Code 1 (responds fine):

[self setConnection];
}
- (void)setConnection{
    NSLog(@"setting myConnection with request");
    myConnection = [[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:requestURL] delegate:self] autorelease];   
}

Log 1:
2010-02-25 10:44:04.384 Untitled[1002:207] setting myConnection with request
2010-02-25 10:44:06.093 Untitled[1002:207] didReceiveResponse
2010-02-25 10:44:06.094 Untitled[1002:207] didReceiveData
2010-02-25 10:44:06.094 Untitled[1002:207] DidFinishLoading

Code 2:
[NSThread detachNewThreadSelector:@selector(setConnection) toTarget:self withObject:nil];   
}
- (void)setConnection{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSLog(@"setting myConnection with request");
    myConnection = [[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:requestURL] delegate:self] autorelease];   
    [pool release];
}

Log 2:
2010-02-25 10:40:50.280 Untitled[972:4003] setting myConnection with request


Delegates:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  { 
    NSLog(@"didReceiveResponse");
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  { 
    NSLog(@"didReceiveData");
}  
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@"DidFinishLoading");
}

Why is that? What is the correct way for sending a request & receiving a response- without freezing the main thread / UI..

Thanks-

Nir.

+1  A: 

It doesn't work because the thread is finished before your class actually executed all it’s code. All you need to do now is start the run loop so the thread doesn't exit and the download can work.

[[NSRunLoop currentRunLoop] run];

You can see this mini tuto here: NSURLConnection in it's own thread

Yannick L.
+2  A: 

From the NSURLConnection documentation:

For the connection to work correctly the calling thread’s run loop must be operating in the default run loop mode.

and

Note that these delegate methods will be called on the thread that started the asynchronous load operation for the associated NSURLConnection object.

In your case, what probably happen is the thread is finished before your class actually executed all it’s code.

Read this for a solution on how to start the run loop: http://www.depl0y.com/2009/02/20/nsurlconnection-in-its-own-thread/

Or, create a second thread and avoid issues of runloops altogether by doing a NSURLConnection sendSynchronousRequest:returningResponse:error, for which no special threading or run loop configuration is necessary in the calling thread.
Do not forget to call back to the main thread via performSelectorInMainThread:

Guillaume