【发布时间】:2018-02-27 06:40:39
【问题描述】:
我有一些工作代码从远程 Web 服务器上的 MySQL 数据库中获取结果。它不再工作,我不断收到消息responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)。这是一些代码...
Alamofire.request(ADS_URL, method: .get).validate().responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success(let value):
let json = JSON(value)
print ("JSON: \(json)")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
case .failure(let error):
print("Error while querying database: \(String(describing: error))")
return
}
}
我也在使用 SwiftyJSON。下面是代码的结果...
Request: Optional(http://doyouado.com/adscan/get_ads)
Response: Optional(<NSHTTPURLResponse: 0x17502f3a0> { URL: http://doyouado.com/adscan/get_ads } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Mon, 18 Sep 2017 16:04:37 GMT";
Server = "nginx/1.12.1";
"Set-Cookie" = "ado_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%225019d90891c70c81df8ebc2fe754a68f%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A15%3A%22109.150.214.128%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A86%3A%22ADoBroadcaster%2F1.0+%28com.GaryFrank.ADoBroadcaster%3B+build%3A1%3B+iOS+10.3.3%29+Alamofire%2F4.5.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1505750677%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D3130ef6f5541e6f944da5a5a1292350bf203fa1b; expires=Mon, 18-Sep-2017 18:04:37 GMT; Max-Age=7200; path=/";
} })
Result: FAILURE
Error: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
我曾尝试使用.response 和.responseString,但没有返回任何信息。我完全被难住了。这一切都很好。希望有人可以对此有所了解吗?
【问题讨论】:
-
你确定 url 指向一个有效的 json 吗?
-
URL 是一个查询 MySQL 并以 JSON 格式返回结果的 php 脚本。 echo json_encode($ads);
-
尝试使用
responseString而不是responseJSON并打印出response.result.value,看看为什么它无法序列化。您可能正在获取 html 或其他内容。 -
使用responseString,会返回一个空字符串给response.result.value。如果我将 URL 放在浏览器中,我可以看到 JSON 格式的数据。我检查了 JSON。它是有效的。
-
@boidkan 谢谢,对我很有用!
标签: swift alamofire swifty-json