繁体   English   中英

如何使用Alamofire Swift 4以JSON编码方式传递数据

[英]How to pass data in JSON Encoding with Alamofire Swift 4

无法弄清楚如何使用Alamofire .post方法将日期传递到服务器。 我必须像这样形成JSON主体:

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

我被困在“位置”属性上。 可能必须是具有一个location属性(是字符串类型)的对象数组。 目前,我的代码是:

@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)
                        }
    }
}

请帮忙。

你可以试试

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

如果您的API请求接受特定的字符串格式,则您需要使用DateFormatter将字符串格式的Date转换为String;否则,如果您接受Date对象,则可以传递但Date对象,但这可能是不可能的。 因此,请尝试使用由服务器参数决定的以字符串格式转换日期的第一个选项。

或者,如果可能,请在服务器上共享请求参数类型支持。

你可以尝试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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