如何为put方法Alamofire Request提供多个编码参数

时间:2018-01-25 19:40:45

标签: swift alamofire

我的请求链接是:http://et.net/webservice/put/profile?api_key=[K]&m=[M]&profile={"birthday":"1994-01-01", "gender":"MALE", "marital":"SINGLE"}

api_keym是网址值,profile是JSON

    let parameters: Parameters = ["api_key": apiKey,
                                  "m": mobile,
                                  "profile": ["birthday":"",
                                              "gender": "Male",
                                              "marital": "Single"]]

1 个答案:

答案 0 :(得分:1)

如果您需要网址中的内容,则必须对其进行百分比编码。您可以使用URLComponents

执行此操作

因此,根据需要构建您的JSON字符串:

let dictionary = [
    "birthday": "1994-01-01",
    "gender": "MALE",
    "marital": "SINGLE"
]
let data = try! JSONEncoder().encode(dictionary)
let jsonString = String(data: data, encoding: .utf8)!

然后您可以构建URL并执行请求:

let urlString = "http://et.net/webservice/put/profile"

var components = URLComponents(string: urlString)!
components.queryItems = [
    URLQueryItem(name: "api_key", value: "[K]"),
    URLQueryItem(name: "m", value: "[M]"),
    URLQueryItem(name: "profile", value: jsonString)
]

Alamofire.request(components.url!, method: .put)
    .response { response in
         // do whatever you want
}

如果您正在构建.post请求,可以让Alamofire将此编码为您的请求正文:

let parameters = [
    "api_key": "[K]",
    "m": "[M]",
    "profile": jsonString
]

Alamofire.request(urlString, method: .post, parameters: parameters)
    .response { response in
        // do whatever you want
}