-1
我有我的銀行代碼Swift HTTP Json請求返回錯誤域= NSCocoaErrorDomain代碼= 3840「沒有值。」的UserInfo = {NSDebugDescription =無值。}
var request = URLRequest(url: URL(string: "http://www.website.com/Application/profile.php")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let postString = "get_comments=\(PostId)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error!)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [Any]
print(jsonData)
} catch {
print(error)
}
}
task.resume()
而且在profile.php這一請求,我有這樣的代碼
if (isset($_POST['get_comments'])) {
$PostId = $_POST['get_comments'];
$response=["For errors",0,"Username"];
echo json_decode($response);
}
但這個代碼返回此以下錯誤
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
當我打印data
它打印「0字節」。我試着做什麼其他的答案建議加上 request.addValue("application/json", forHTTPHeaderField: "Content-Type")
,但它並沒有改變任何東西
你的Swift代碼有幾個不好的做法,但錯誤本身似乎是在後端。對於Swift部分:不要使用'.mutableContainers',它在'Swift'中沒有效果。另外,將'JSON'強制轉換爲'Any'數組通常是個壞主意。你確定你的'API'不希望'POST'請求的正文中有'JSON'數據嗎?目前你沒有發送'JSON',但你試圖將響應解碼爲'JSON'。 –
@DávidPásztor我誤以爲'json_encode'爲'json_decode',但即使在改變它之後也沒有任何改變。 – sakoaskoaso
預期的請求體是什麼?你確定,它應該是'.utf8'編碼數據而不是'JSON'? –