Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show GET request in Label

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];
}
like image 454
Evgenii Avatar asked Dec 21 '25 03:12

Evgenii


1 Answers

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?

like image 64
Matz Avatar answered Dec 23 '25 17:12

Matz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!