如何在标签中显示 GET 请求

How to show GET request in Label

我的获取请求只能在命令行 NSLog 中工作。 我需要在标签中显示一个数据,但它不起作用。

-(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];
}

虽然我不太确定这里的用法...您正在使用 @getString,我认为这是问题所在。你可能想做这样的事情:

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

这应该与 NSLog 具有相同的行为。

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];       
}];

这里更真实Why should I choose GCD over NSOperation and blocks for high-level applications?

dispatch_async(dispatch_get_main_queue(), ^{
    [self.label setText:someString];
});