如何在Label中显示GET请求(How to show GET request in Label)
我的get请求仅在命令行NSLog中有效。 我需要在Label中显示数据,但它不起作用。
-(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]; }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不在主线程上工作,这是更新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); }); }此代码适用于您。
您还可以使用:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self.label setText:getString]; }];真的更多这里为什么我应该选择GCD而不是NSOperation并阻止高级应用?
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?
更多推荐
发布评论