我是Mac应用程序开发的新手,我们现有的Mac应用程序包含以下代码行
[NSURLConnection sendSynchronousRequest:request returningResonse:response error:Error
警告消息显示为
sendSynchronousRequest在macOS 10.11中已弃用
并建议使用[NSURLSession dataTaskWithRequest:completionHandler:]
我已实现以下代码更改,以按照建议使用NSURLSession,但是它返回的数据值为“ nil”。您能否建议需要做些什么才能获得所需的数据作为响应?
__block NSError *WSerror;
__block NSURLResponse *WSresponse;
__block NSData *myData;
NSURLSession *session =[NSURLSession sharedSession];
[[session completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
myData = data;
WSresponse =response;
WSerror = error;
}] resume];
NSString *theXml = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
return theXml;
答案 0 :(得分:0)
完成处理程序是异步的。您必须在内部完成处理程序中完成工作。
__block
声明毫无意义。
NSURLSession *session =[NSURLSession sharedSession];
[[session completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSString *theXml = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
// do something with `theXml`
}
}] resume];