JSON to display text -- Freezes UI
- by Adam Storr
Hi everyone,
I currently have a very simple view which displays info from a JSON feed. The problem I'm facing is the few second pause I encounter once I press this tab. How can I make this view load instantly and then have the label.text areas load after? Preferable with an activity indicator?
Should I use threads?
Thanks in advance!
Code:
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *)downloadStats {
id response = [self objectWithUrl:[NSURL URLWithString:@"http://www.example.com/JSON"]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
[feed release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[GlobalStatsScrollView setScrollEnabled:YES];
[GlobalStatsScrollView setContentSize:CGSizeMake(320, 360)];
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"View appears");
// Download JSON Feed
NSDictionary *feed = [self downloadStats];
totalproduced.text = [feed valueForKey:@"Produced"];
totalno.text = [feed valueForKey:@"Total"];
mostcommon.text = [feed valueForKey:@"Most Common"];
}