NSURLSessionDataTask不执行完成处理程序块 [英] NSURLSessionDataTask not executing the completion handler block
问题描述
我正在尝试从本地节点服务器中提取一些数据.服务器正在获取get请求并将其记录下来,但是由于某种原因,我的iOS应用程序将无法执行我在完成处理程序中拥有的任何代码.这是代码:
I am trying to pull some data from my local node server. The server is getting the get request and logging it, but for some reason my iOS app will not execute any of the code that I have in the completion handler. Here is the code:
- (IBAction) buttonPressed{
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:3000/"];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error){
nameLabel.text = @"yay!";
/*
if (!error){
nameLabel.text = @"noerr";
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
if (httpResp.statusCode == 200){
NSError *jsonErr;
NSDictionary *usersJSON =
[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonErr];
if (!jsonErr){
// nameLabel.text = usersJSON[@"username"];
nameLabel.text = @"nojerr";
}
else{
nameLabel.text = @"jsonErr";
}
}
}
else{
nameLabel.text = @"Err";
}
*/
}];
[dataTask resume];
}
运行程序时,nameLabel不会更改为"yay".但是,如果我尝试在NSURLSessionDataTask行之前更改nameLabel,它将更改.
When the program is run, the nameLabel is not changed to "yay". However if I try to change the nameLabel before the NSURLSessionDataTask line, it changes.
推荐答案
NSURLSessionDataTask
在后台线程中运行.要更新用户界面中的任何内容,例如标签,按钮,表格视图等,您必须在主线程上进行.如果要从completionHandler
块更新标签文本,则需要在主线程中更新标签,如下所示:
NSURLSessionDataTask
runs in a background thread. To update anything in the user interface such as labels, buttons, table views, etc, you must do so on the main thread. If you want to update the label text from the completionHandler
block then you need to update the label in the main thread like so:
dispatch_sync(dispatch_get_main_queue(), ^{
nameLabel.text = @"yay!";
});
这篇关于NSURLSessionDataTask不执行完成处理程序块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!