gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:24 26 4
gpt4 key购买 nike

我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com