3

My get request works only in command line NSLog. I need to show a data in Label, but it doesn't works.

-(void)getRequest{

  NSURLSessionConfiguration *getConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *getSession = [NSURLSession sessionWithConfiguration: getConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];
  NSURL * getUrl = [NSURL URLWithString:@"http://localhost:3000/get"];
  NSURLSessionDataTask * getDataTask = [getSession dataTaskWithURL:getUrl completionHandler:^(NSData *getData, NSURLResponse *getResponse, NSError *getError) {
    if(getError == nil){
       NSString * getString = [[NSString alloc] initWithData: getData encoding: NSUTF8StringEncoding];
       [self.label setText:getString];// doesn't work!
       NSLog(@"Data = %@",getString);}//  it works!!
       MainViewController*l=[[MainViewController alloc]init];

       [l getRequest];
    }
 ];

 [getDataTask resume];
}
shim
  • 9,289
  • 12
  • 69
  • 108
Evgenii
  • 422
  • 2
  • 14

3 Answers3

2

dataTaskWithURL is not working on the main-thread and that's necessary to update your UI.

if (getError == nil) {
    NSString * getString = [[NSString alloc] initWithData: getData encoding: NSUTF8StringEncoding];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.label setText: getString];
        NSLog(@"Data = %@", getString);

    });

    }

This code will work fine for you.

You can also use:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self.label setText:getString];       
}];

Real more here Why should I choose GCD over NSOperation and blocks for high-level applications?

Community
  • 1
  • 1
Matz
  • 1,006
  • 10
  • 27
1

While I'm not quite sure what the usage would be here...you are using @getString, which I think is the issue. You probably want to do something like:

[self.label setText:[NSString stringWithFormat:"Data = %@", getString];

That should have the same behavior as NSLog.

BHendricks
  • 4,423
  • 6
  • 32
  • 59
1
dispatch_async(dispatch_get_main_queue(), ^{
    [self.label setText:someString];
});
Tanakorn.K
  • 150
  • 9