我使用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