【发布时间】:2017-09-13 04:05:02
【问题描述】:
我正在使用 Guzzle 从 PHP 调用公共 API。它返回有效的 JSON(在 JSONLint.com 上验证)。但是,当我尝试将其返回到我的 iOS 应用程序时,Alamofire 不喜欢它。我尝试解码 JSON,然后重新编码,但我得到了相同的结果。我不明白为什么 Alamofire 不接受它。我已经用 Paw 测试了 Web 服务,它返回一个带有 content-type 和 application/json 的 JSON 结果。
我得到的错误是:
由于错误,无法序列化 JSON:无法序列化数据 阅读,因为它的格式不正确。
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);
Swift 代码:
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。
标签: php ios swift alamofire guzzle