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());
}
July 10th, 2011 - 20:55
Oh gosh, I’m so glad I found this helpful blog, I have been having so many problems with getting tiles to load on my map. You’re my hero.
September 3rd, 2011 - 22:20
how do you know which request goes with which tile and then force it to draw? That’s what’s I’m having difficulty with.