简体   繁体   中英

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.

You can try

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

if your API request accepts particular string formate then you need to convert Date in String formate with DateFormatter or else if that accept Date Object then you pass but Date object but that's maybe not possible. so please try with first option Convert date in string format which is predecided by server parameter.

or if possible then share request parameter type support on your server.

you can try with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM