使用manager.request和POST

时间:2017-06-19 20:36:43

标签: ios swift3 alamofire

我想向Alamofire POST发送SessionManager请求。

我阅读了文档 https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol

但我没有看到使用请求和POST的示例,只能上传。

它给出的例子:

let parameters: Parameters = ["foo": "bar"]

Alamofire.request(urlString, parameters: parameters) // Encoding => URLEncoding(destination: .methodDependent)
Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding(destination: .queryString))
Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding(destination: .httpBody))

// Static convenience properties (we'd like to encourage everyone to use this more concise form)
Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.queryString)
Alamofire.request(urlString, parameters: parameters, encoding: URLEncoding.httpBody)

我的代码是:

manager.request(url, method: .post, parameters: parameters, encoding: .url) .responseJSON { response in fulfill(response) }

符合方法签名(据我所知),但我在调用中收到错误“额外参数method:

1 个答案:

答案 0 :(得分:1)

您需要将URLRequest与身体中的参数一致Data

此代码可以帮助您

    var request = URLRequest(url: urlString!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)

    manager.request(request)
           .responseJSON { response in
                fulfill(response)
        }

希望这有帮助