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];
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With