Swift 4 Codable Struct with Post Request

Viewed 4126

i want to send a url.request(POST)with a Codable Struct like That :

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

and my request is like that :

 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()

and of the Server Side i have this PHP Script:

<?php
    print_r($_POST);
?>

but i am receiving :

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

my Problem is that i can't get the Keys with the value on my PHP..

what is wrong with the code ?

1 Answers

Finally, answer is :

if you want to work with the response string just go and decode the "data"

For example :

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

in realData you can work with the data, but you need to create Codable/decobale Struct to work with

response is my coddle/decodable struct

or :

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