Kev*_*lia 39 httpresponse http-status-code-403 ios swift alamofire
我正在点击偶尔会抛出HTTP 403错误的API,响应机构可以以json的形式提供一些额外的信息,但是对于我的生活,我似乎无法从Alamofire中获取信息响应对象.如果我通过chrome访问API,我会在开发人员工具中看到这些信息.这是我的代码:
Alamofire.request(mutableURLRequest).validate().responseJSON() {
(response) in
switch response.result {
case .Success(let data):
if let jsonResult = data as? NSDictionary {
completion(jsonResult, error: nil)
} else if let jsonArray = data as? NSArray {
let jsonResult = ["array" : jsonArray]
completion(jsonResult, error: nil)
}
case .Failure(let error):
//error tells me 403
//response.result.data can't be cast to NSDictionary or NSArray like
//the successful cases, how do I get the response body?
}
Run Code Online (Sandbox Code Playgroud)
我几乎查询了附加到响应的每个对象,但是在HTTP错误的情况下它似乎没有给我回复响应主体.有没有解决方法或我在这里缺少的东西?
Kev*_*lia 84
我在他们的github页面上问了这个问题并得到了cnoon的回答:
迅捷2:
if let data = response.data {
let json = String(data: data, encoding: NSUTF8StringEncoding)
print("Failure Response: \(json)")
}
Run Code Online (Sandbox Code Playgroud)
迅捷3:
if let data = response.data {
let json = String(data: data, encoding: String.Encoding.utf8)
print("Failure Response: \(json)")
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/Alamofire/Alamofire/issues/1059
我只是省略了编码部分,通过这样做,你甚至可以在出错的情况下得到响应json.
Swift 5 在 DefaultDataResponse 扩展中轻松获得身体响应:
String(data: data!, encoding: String.Encoding.utf8)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19269 次 |
| 最近记录: |