Question

I started out using asynchronism but to get the returned data became a hassle. I then began using class methods which, I believe, ruled out the possibility of using the delegate methods. So I kept with the synchronous, knowing that this would be an issue but didn't think I would have this much difficulty with a solution. What is the best way to retrieve data whilst keeping the UI interact-able?

Was it helpful?

Solution

Synchronous NSURLConnections work great inside of an NSOperation - and because you are using them synchronously, an NSOperationQueue handed the NSOperations will automatically use a background thread to run them (you have to do extra work otherwise).

Having URL connections operate in a background thread is the key to keeping the UI responsive, something that an asynchronous NSURLOperation does not do by default (look at what thread the data callbacks all come in on).

Sometimes you want to handle data incoming (like if you have a progress bar) and in those cases asynchronous URL connections are better, they can still be in an NSOperation.

Because this is frustrating you, you may well want to take a look at the alternative ASIHTTPRequest library, also based on NSOperation but it seems like it may make some of this less painful for you (they have good example code):

http://allseeing-i.com/ASIHTTPRequest/

OTHER TIPS

The NSURLConnection synchronous call should be able to be stuck in a background thread, but I strongly recommend you deal with the 'hassle', and do it The Right Way™. The best way to retrieve data whilst keeping the UI interactive is to use NSURLConnection's asynchronous methods.

Out of interest what issues where you having with getting the data? I found using async NSURLConnection and a NSNotificaion when it had finished to be quite a handy solution.

In the class where you need the data (I normally put it in the init method)

-(id)init{
    ... object setup ...
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateView) name:@"ScanCompleted" object:nil];
}

updateView is the method to be called when the connection has finished receiving data

in the NSURLConnection

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

//Notify that we are finished
[[NSNotificationCenter defaultCenter] postNotificationName:soapAction object:self];

}

This works for me quite nicely - the NSURLConnection is threaded so the UI doesn't lock up and it gets updated when the data has finished downloading.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top