In my view I attempt to display some weather related info. I use
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Make NSURL and other related things
Send NSURLRequest
Set 2 UILabels to data
NSLog(Show data retrieved)
});
For some reason, I see the NSLog line roughly 15-45 seconds before the uilabel changes to the new text. I am fairly new to Obj-C and a lot of my code comes from using tutorial so I dont have the greatest understanding of the dispatch_async method. Any thoughts or suggestions would be appreciated.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLResponse *response = nil;
NSError *error = nil;
NSData *respData = nil;
NSURLRequest *forecastRequest = [NSURLRequest requestWithURL:currentForecastUrl];
respData = [NSURLConnection sendSynchronousRequest:forecastRequest returningResponse:&response error:&error];
[_responseData appendData:respData];
NSLog(@"Response: %@", response);
NSLog(@"Error: %@", error);
id JSON = [_responseData yajl_JSON];
currentForecast = [[NSArray alloc]initWithObjects:[JSON objectForKey:@"temperature"],[JSON objectForKey:@"feelsLike"],nil];
[_temperatureLabel setText:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"temperature"]]];
[_tempDescriptionLabel setText:[NSString stringWithFormat:@"%@",[JSON objectForKey:@"desc"]]];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2.0];
[_tempDescriptionLabel setAlpha:1];
[_temperatureLabel setAlpha:1];
[UIView commitAnimations];
NSLog(@"Done");
NSLog(@"JSON: %@", [JSON yajl_JSONStringWithOptions:YAJLGenOptionsBeautify indentString:@" "]);
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
is used for create a background thread, but the user interface should be updated in the Main Thread
like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//do stuff in background
dispatch_async(dispatch_get_main_queue(), ^{
// Update your UI
});
});