将多个数据附加到URLRequest的httpbody

时间:2019-08-27 08:30:58

标签: ios swift nsurlrequest

我想将另一个字典作为参数附加到httpBody的{​​{1}}

请求模型:

URLRequest

Api请求:

struct RequestModel: Encodable {

    let body: Body
}

struct Body: Encodable {
    let name: String
    let score: String
    let favList: [String]
}

另一本字典:do { var urlRequest = URLRequest(url: resourceURL) urlRequest.httpMethod = kHTTPMethodPOST urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = try JSONEncoder().encode(self.requestModel) let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let jsonData = data else { completion(.failure(.responseError)) return } } dataTask.resume() } catch { completion(.failure(.unknownError)) }

airports

试图将var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] 字典参数附加到airports,但不能附加。

感谢您的帮助和建议!

谢谢

2 个答案:

答案 0 :(得分:1)

POST JSON的常用语法是

do { 
    var urlRequest = URLRequest(url: resourceURL)
    urlRequest.httpMethod = "POST"
    let postData = try JSONEncoder().encode(self.requestModel)
    urlRequest.httpBody = postData
    urlRequest.setValue("\(postData.count)", forHTTPHeaderField:"Content-Length")
    urlRequest.setValue("application/json", forHTTPHeaderField:"Accept")
    urlRequest.setValue("application/json", forHTTPHeaderField:"Content-Type")

}

答案 1 :(得分:1)

如果您必须将airports词典附加到请求正文中,则可能需要将其包括在Request模型本身中。

我建议更新您的RequestModel并使其为Encodable

并将airports字典作为RequestModel的一部分

类似这样的东西

struct RequestModel: Encodable {

    let body: Body
    let airportsDict: [String:String]
}

struct Body: Encodable {
    let name: String
    let score: String
    let favList: [String]
}

这样,您的httpBody将拥有您要传递的所有数据。

希望这会有所帮助