ios 如何在AFJSONRequestOperation的回调中从NSHTTPURLResponse中获取响应数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10627815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the response data out of the NSHTTPURLResponse in the callback of AFJSONRequestOperation?
提问by Todd Hopkinson
I have a situation where I need to access the raw response data for an AFJSONRequestOperation, from within the callback block which includes only NSHTTPURLResponse. I am able to get the statusCode from the NSHTTPURLResponse, but don't see any way to get to the raw data. Is there a good way that anyone knows of to access this from the failure callback block of this operation?
我有一种情况,我需要从仅包含 NSHTTPURLResponse 的回调块中访问 AFJSONRequestOperation 的原始响应数据。我能够从 NSHTTPURLResponse 中获取 statusCode,但看不到任何获取原始数据的方法。有没有人知道从这个操作的失败回调块访问它的好方法?
回答by mattt
NSHTTPURLResponse
only contains HTTP header information; no body data. So no, this would be impossible. If you have any control over this code, have the block or method pass the operation itself and get responseData
or responseJSON
.
NSHTTPURLResponse
只包含 HTTP 头信息;没有身体数据。所以不,这是不可能的。如果您对此代码有任何控制权,请让块或方法传递操作本身并获取responseData
或responseJSON
。
回答by spnkr
In the callback from responseJSON
you can get the body from a DataResponse<Any>
object using response.result.value
or String(data:response.data!, encoding: .utf8)
.
在回调中,responseJSON
您可以DataResponse<Any>
使用response.result.value
或从对象中获取主体String(data:response.data!, encoding: .utf8)
。
You can't get it from response.response
, which is a NSHTTPURLResponse
object. This only has header info.
你不能从response.response
,它是一个NSHTTPURLResponse
对象。这只有标题信息。
Alamofire.request(URL(string: "https://foo.com")!).validate(statusCode: 200..<300).responseJSON() { response in
let body = response.result.value
}
If the http response doesn't validate the above doesn't work. but this does:
如果 http 响应未验证上述内容不起作用。但这确实:
Alamofire.request(URL(string: "https://foo.com")!).validate(statusCode: 200..<300).responseJSON() { response in
let body = String(data:response.data!, encoding: .utf8)
}
回答by 7Cornelio
Old question, but anyway...
老问题,但无论如何......
You don't need to get to the operation object, you can easily do something like:
您不需要访问操作对象,您可以轻松执行以下操作:
NSData * data = [NSJSONSerialization dataWithJSONObject:JSON options:0 error:nil]];
With the JSON id that the callback receives.
使用回调接收的 JSON id。