任何方式来获取响应正文HTTP错误?
我碰到一个偶尔会抛出HTTP 403错误的API,响应主体可以以json的forms提供一些额外的信息,但是对于我来说,我似乎无法从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? }
我已经查询了附加到响应的每个对象,但是在HTTP错误的情况下,它似乎没有给我回应主体。 有没有变通或我在这里失踪的东西?
我在他们的github页面上问了这个问题,并从cnoon得到了一个答案:
迅捷2:
if let data = response.data { let json = String(data: data, encoding: NSUTF8StringEncoding) print("Failure Response: \(json)") }
迅捷3:
if let data = response.data { let json = String(data: data, encoding: String.Encoding.utf8) print("Failure Response: \(json)") }
https://github.com/Alamofire/Alamofire/issues/1059
我只是遗漏了编码部分,通过这样做,即使出现错误,您也能够获得响应json。
- 如何将json数据从alamofire转换为swift对象
- 如何在Swift3中使用alamofire与对象映射器来映射数组中的数组?
- 在Alamofire连接之前调用numberOfRowsInSection
- Swift – 如何使用AlamofireImage / ImageShack节省内存?
- Twitter应用程序专用authentication总是返回401
- 如何在Alamofire中实施自签名证书?
- types不符合协议“URLRequestConvertible”与Alamofire
- Alamofire清除所有的cookies
- 使用Alamofire上传具有base64String编码多个图像的数组