【问题标题】:How to show GET request in Label如何在标签中显示 GET 请求
【发布时间】:2016-06-07 11:16:30
【问题描述】:

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

【问题讨论】:

  • 你能检查你的标签是否为 nil 吗?通过在块中放置NSLog(@"Data = %@", self.label);

标签: ios objective-c uilabel get-request


【解决方案1】:

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?

【讨论】:

    【解决方案2】:

    虽然我不太确定这里的用途是什么...您使用的是@getString,我认为这是问题所在。您可能想要执行以下操作:

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

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

    【讨论】:

      【解决方案3】:
      dispatch_async(dispatch_get_main_queue(), ^{
          [self.label setText:someString];
      });
      

      【讨论】:

        猜你喜欢
        • 2023-01-27
        • 2013-09-14
        • 1970-01-01
        • 2015-07-17
        • 2022-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-03
        相关资源
        最近更新 更多