Swift HTTP Json请求返回Error Domain = NSCocoaErrorDomain Code = 3840“No value。” UserInfo = {NSDebugDescription =无值。}

时间:2017-08-09 09:35:44

标签: json swift

我在Swift代码中有这个请求

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"),但它没有改变任何东西

1 个答案:

答案 0 :(得分:0)

PostId是可选值,我忘了添加!。请求看起来像

get_comments="Optional("12")"这是错误的。