我使用Guzzle从PHP调用公共API。它返回有效的JSON(在JSONLint.com上进行验证)。但是,当我尝试将其返回给我的iOS应用程序时,Alamofire不喜欢它。我尝试解码JSON,然后重新编码它,但我得到相同的结果。我无法弄清楚为什么Alamofire不会接受它。我已经使用Paw测试了Web服务,并且它返回了content-type
的application/json
的JSON结果。Alamofire不会将结果识别为JSON
我得到的错误是:
JSON could not be serialized because of error: The data couldn’t be read because it isn’t in the correct format.
PHP代码:
$url = "myUrl";
$client = new GuzzleHttp\Client();
$res = $client->get($url, [
'headers' => [
'Authorization' => "Bearer myKey",
'Accept' => 'application/json'
]
]);
header('Content-type: application/json');
$results = $res->getBody();
$this->response($results, 200);
斯威夫特代码:
let url = serviceUrl + "currentwar"
let params = [
"clanId" : "\(clanId)",
]
Alamofire.request(url, parameters: params, encoding: URLEncoding.default)
.validate()
.responseJSON { (response) in
switch response.result {
case .success(let data):
self.json = JSON(data)
print(self.json as Any)
// process data
DispatchQueue.main.async(execute: {() -> Void in
// populate view
})
case .failure(let error):
print("An error occurred: \(error.localizedDescription)")
}
}
尝试使用'responseString',而不是'responseJSON'和字符串转换成JSON和解析。 –
@BadhanGanesh,我试过这个,但似乎无法对结果字符串做任何事情。将其转换为JSON只返回null。 – Lastmboy