NSURLSession dataTaskWithRequest返回零数据

时间:2020-07-21 08:41:39

标签: objective-c macos nsurlsession

我是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;

1 个答案:

答案 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];
相关问题