fullstop.
9Jul/112

NSURLConnection in a Background Thread

YUSU App Map

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());
}
Comments (2) Trackbacks (0)
  1. 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.

  2. 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.


Leave a comment

(required)

No trackbacks yet.

  • RSS
  • Twitter
  • Facebook