[英]Alamofire responseSerializationFailed
I am using Alamofire to make request in my swift app.我正在使用 Alamofire 在我的 swift 应用程序中发出请求。 All of my request were working 2 days ago and now only some of them are working.我的所有请求在 2 天前都有效,现在只有其中一些有效。 My API is working correctly, I get the correct response using Postman and in the Android version of my app.我的 API 工作正常,我使用 Postman 和我的应用程序的 Android 版本得到了正确的响应。
Here is the request code这是请求代码
let headers: HTTPHeaders = [
"Authorization": "\(token)",
"Accept": "application/json"
]
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON(completionHandler: { (response) in
deactivateActivityIndicator()
if let json = response.result.value {
log.debug("User json: \(json)")
let user = Mapper<User>().map(JSON: JSON(json).dictionaryObject!)
self.delegate?.getRequestSuccessful(user!)
}
else{
self.delegate?.requestError("Error occurred getting response from API")
}
})
The JSON I am requesting from my API looks as follows:我从 API 请求的 JSON 如下所示:
{
"id": "1",
"email": "test@test.com",
"first_name": "Test",
"last_name": "Tester",
"role": 1,
"verified": true,
"edited": "2018-08-14T11:52:31.900Z",
"created": "2018-08-14T08:02:59.251Z"
}
I keep getting a 401
response as follows:我不断收到401
响应,如下所示:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 “字符 0 周围的值无效。” UserInfo={NSDebugDescription=字符 0 周围的值无效。}))
I have tried change from responseJSON
to responseString
like in the question here but it did not fix the problem我试图从改变responseJSON
到responseString
在这个问题就像在这里,但它并没有解决问题
Please try with JSONEncoding.default .请尝试使用 JSONEncoding.default 。 in place of URLEncoding.default in your existing code代替现有代码中的 URLEncoding.default
I managed to fix the issue after a couple of days of searching and debugging.经过几天的搜索和调试,我设法解决了这个问题。 When entering the URL for the Alamofire request I was using the URL formatted like https:///www.test.com
.在输入 Alamofire 请求的 URL 时,我使用的 URL 格式为https:///www.test.com
。 I added an extra slash at the end as follows https:///www.test.com/
我在末尾添加了一个额外的斜线,如下所示https:///www.test.com/
According to what I found, the request will get redirected to the correct URL and the headers are not sent along with the request.根据我的发现,请求将被重定向到正确的 URL,并且标头不会与请求一起发送。 Thus explaining the 401 response (Unauthorized)从而解释 401 响应(未经授权)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.