Frankie Nwafili Frankie Nwafili - 1 year ago 134
Objective-C Question

NSURLSessionDataTask not executing the completion handler block

I am trying to pull some data from my local node server. The server is getting the get request and logging it, but for some reason my iOS app will not execute any of the code that I have in the completion handler. Here is the code:

- (IBAction) buttonPressed{
NSURL *url = [NSURL URLWithString:@""];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error){
nameLabel.text = @"yay!";
if (!error){
nameLabel.text = @"noerr";
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
if (httpResp.statusCode == 200){
NSError *jsonErr;

NSDictionary *usersJSON =
[NSJSONSerialization JSONObjectWithData:data

if (!jsonErr){
// nameLabel.text = usersJSON[@"username"];
nameLabel.text = @"nojerr";

nameLabel.text = @"jsonErr";
nameLabel.text = @"Err";
[dataTask resume];


When the program is run, the nameLabel is not changed to "yay". However if I try to change the nameLabel before the NSURLSessionDataTask line, it changes.

Answer Source

NSURLSessionDataTask runs in a background thread. To update anything in the user interface such as labels, buttons, table views, etc, you must do so on the main thread. If you want to update the label text from the completionHandler block then you need to update the label in the main thread like so:

dispatch_sync(dispatch_get_main_queue(), ^{
  nameLabel.text = @"yay!";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download