ios - 如何在标签中显示 GET 请求

标签 ios objective-c uilabel get-request

我的 get 请求仅在命令行 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];
}

最佳答案

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?

关于ios - 如何在标签中显示 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35614467/

相关文章:

iphone - NSSearchPathForDirectoriesInDomains 的问题

ios - 在应用程序中导入照片选项

iphone - 单击 objective-c 中的按钮更改图像

ios - 如何重用另一个类的 UITableView

ios - RestKit 添加属性映射和关系映射

ios - 根据当前时间更改标签文本和颜色

ios - 为什么 AWS 开发工具包 2.2.0 不识别 BFTask?

iphone - 如何使用 UITableView 中的标题部分展开和折叠行

ios - TableView 中的可扩展 View

ios - 在 UIImageView 上设置顶部约束会导致 UILabel 的高度固定