I wanted to update the UI in the NSURLSession's completion block. The initial implementation didn't update the UI immediately. It updated the UI maybe 20 seconds later. Here is the initial implementation.
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 150, 150)];
label.backgroundColor = [UIColor greenColor];
label.text = jsonDict[@"object_or_array"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:label];
});
}];
[task resume];
I moved the location of the label.text = jsonDict[@"object_or_array"] inside the main queue as following.
dispatch_async(dispatch_get_main_queue(), ^{
label.text = jsonDict[@"object_or_array"]
[self.view addSubview:label];
});
Then the UI was updated immediately as expected.
Could anyone tell me why this is?
UIImageobjects in a background thread. From theUIViewdocs: "Manipulations to your application’s user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread."