I can’t seem to find any info on this question, so I thought I’d ask the community.
Basically, I have a UITableView and I want to show an activity indicator while its data is loading from my server.
Here is some example code of what I’m trying to do (I’m using ASIHttpRequest).
//self.listData = [[NSArray alloc] initWithObjects:@"Red", @"Green", @"Blue", @"Indigo", @"Violet", nil]; //this works
NSString *urlStr=[[NSString alloc] initWithFormat:@"http://www.google.com"]; //some slow request
NSURL *url=[NSURL URLWithString:urlStr];
__block ASIHTTPRequest *request=[ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setCompletionBlock:^{
self.listData = [[NSArray alloc] initWithObjects:@"Red", @"Green", @"Blue", @"Indigo", @"Violet", nil]; //this doesn't work...
[table reloadData];
}];
[request setFailedBlock:^{
}];
[request startAsynchronous];
The dummy request to google.com does nothing – it just creates a delay and in the response I hope to repopulate the table with some JSON response from my own website.
But when I try to populate the table with the colours, nothing happens! I just get a blank table… If I uncomment the line above, it works fine, it’s just on http responses things don’t work for me.
Any suggestions greatly appreciated.
Edit:
I did a [self.tableView reloadData]; and now it works…
NSURLConnectionis not hard to use and will result in better, more performant code.UITableView. Again, I recommend Core Data.I would suggest reviewing how MVC works, you are short circuiting the design and that is the core problem.
SPOILER
Here is a more detailed how to. First you want the data retrieval to be async. Easiest and most reusable way to do that is build a simple NSOperation subclass.
This subclass is the most basic way to download something from a URL. Construct it with a
NSURLRequestand a delegate. It will call back on a success or failure. The implementation is only slightly longer.Now this class is VERY reusable. There are other delegate methods for NSURLConnection that you can add depending on your needs.
NSURLConnectioncan handle redirects, authentication, etc. I strongly suggest you look into its documentation.From here you can either spin off the
CIMGFSimpleDownloadOperationfrom yourUITableViewControlleror from another part of your application. For this demonstration we will do it in theUITableViewController. Depending on your application needs you can kick off the data download wherever makes sense. For this example we will kick it off when the view appears.Now when the view appears an async call will go and download the content of the URL. In this code that will either pass or fail. The failure first:
On success we need to parse the data that came back.
And done. A few more lines of code for you to write but it replaces 13K+ lines of code that gets imported with ASI resulting in a smaller, leaner, faster application. And more importantly it is an app that you understand every single line of code.