Search code examples
iosiphoneswiftalamofire

How to pass data in JSON Encoding with Alamofire Swift 4


Can't figure out how to pass date to the server with Alamofire .post method. I have to form JSON body like this:

{
    "title": "My Title",
    "locations": [
        {
            "location": "locationID"
        }
        ],
}

I'm stuck on "locations" property. Probably, it has to be an Array of objects with one location property which is a string type. For this moment my code is:

@IBAction func createEvent(_ sender: Any) {
    let parameters: Parameters = [
        "title": Event.title ?? nil,
        "locations":   //What have I wright here?
    ]

    Alamofire.request(requestURL,
                      method: .post,
                      parameters: parameters,
                      encoding: JSONEncoding.default,
                      headers: headers).responseJSON {response in

                        switch response.result {
                        case .success:
                            print(response)

                        }
                        case .failure(let error):

                            print(error)
                        }
    }
}

Please help.


Solution

  • You can try

    let parameters: Parameters = [
        "title": Event.title ?? nil,
        "locations": [["location":"idherrr"]]
    ]