9Jul/112
NSURLConnection in a Background Thread

Just a quick post to highlight a little issue I was having getting tiles to load from the internet for the campus map in the YUSU iPhone app.
Basically, getting an NSURLConnection to load something asynchronously in a background thread requires a bit of extra work than running it in the main thread (which I needed to do as the CATiledLayer I use loads tiles in the background).
The problem arises from the background thread stopping before the NSURLConnection actually gets any response. Luckily it's pretty easy to force a thread/run loop to keep running with CFRunLoopRun(). Just don't forget to stop it when you're done with CFRunLoopStop(CFRunLoopGetCurrent()).
Here's some sample code:
- (void)startLoadWithURL:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
CFRunLoopRun();
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do something with the finished connection
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Handle the error
CFRunLoopStop(CFRunLoopGetCurrent());
}
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
CFRunLoopRun();
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do something with the finished connection
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Handle the error
CFRunLoopStop(CFRunLoopGetCurrent());
}