具有后请求的Swift 4可编码结构

时间:2017-11-27 21:46:58

标签: php json url swift4 codable

我想发送一个带有Codable Struct的url.request(POST),如:

struct Picklist : Codable {
    var id = Int()
    var ean = String()
    var position = String()
}

我的要求是这样的:

 let request = NSMutableURLRequest(url: NSURL(string: "http://XXX.XX.XX.XX/NEW/index.php")! as URL)
        request.httpMethod = "POST"



                let myID = Picklist.init(id: 3, ean: "asdf", position: "q")
                let encoder = JSONEncoder()
                do {
                    let jsonData = try encoder.encode(myID)
                    request.httpBody = jsonData
                    print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
                } catch {
                    print("ERROR")
                }

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            print("response = \(response)")

            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("responseString = \(responseString)")
        }
        task.resume()

和服务器端我有这个PHP脚本:

<?php
    print_r($_POST);
?>

但我收到了:

responseString = Optional(Array
(
    [{"id":3,"ean":"asdf","position":"q"}] => 
)

我的问题是我无法获得带有PHP值的密钥..

代码有什么问题?

1 个答案:

答案 0 :(得分:1)

最后,答案是:

如果你想使用响应字符串,只需去解码&#34;数据&#34;

例如:

guard let data = data else {return}
            do{
                let realData = try JSONDecoder().decode(response.self, from: data)
                completion(realData)
            }catch let jsonErr{
                print(jsonErr)
            }

在realData中你可以使用数据,但你需要创建Codable / decobale Struct来使用

响应是我的溺爱/可解码结构

或:

let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }