Search code examples
jsonswiftxcodejson-serialization

PUT request in iOS (Swift) with JSONSerialization


I'm trying to update an attribute via PUT request using JSONSerialization. Here is my function :

func updateRGPDStatus(user:UserModel){

        let parameters = ["firstname": user.firsname as Any,
                          "lastname": user.lastname as Any,
                          "mail": user.mail as Any,
                          "has_web_access": user.has_web_access as Any,
                          "has_mobile_access": user.has_mobile_access as Any,
                          "id_user": user.id_user as Any,
                          "has_accepted_rgpd": user.rgpd as Any
            ] as [String : Any]

        guard let url = URL(string: UPDATE_RGPD_STATUS) else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "PUT"

        guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
            return
        }
        request.httpBody = httpBody
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            if let response = response {
                print(response)
            }

            if let data = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    print(json)
                }
                catch {
                    print(error)
                }
            }
        }.resume()

    }

and here is the json that I'm supposed to update :

{
    "user": {
        "firstname": "first_name",
        "lastname": "last_name",
        "mail": "[email protected]",
        "has_web_access": true,
        "has_mobile_access": true,
        "id_user": 17,
        "has_accepted_rgpd": false
    }
}

When I send my request, I got and error of type "missing parameters" because I don't include the "user" attribute in my request which I don't know how to do it at this stage of my learning. Any help please. Thank you ^^


Solution

  • You can try

    let res:[String : Any] = ["firstname": user.firsname as Any,
                          "lastname": user.lastname as Any,
                          "mail": user.mail as Any,
                          "has_web_access": user.has_web_access as Any,
                          "has_mobile_access": user.has_mobile_access as Any,
                          "id_user": user.id_user as Any,
                          "has_accepted_rgpd": user.rgpd as Any
            ]
    
    
    let parameters:[String : Any] = ["user":res] // the new parameters