我将我的项目更新为Swift 3和Alamofire 4.我使用的是自定义编码,但它已改为其他编码方法。我无法找到替代/等同于此:
alamoFire.request(urlString, method: HTTPMethod.post, parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = (body as NSString).data(using: String.Encoding.utf8)
mutableRequest.httpBody = data
return (mutableRequest, nil)
}), headers: headers()).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(responseObject: JSON)
case .failure(let error):
failure(error: responseObject)
}
}
我也尝试过制作URLRequest对象和简单请求它也给我错误
var request = URLRequest(url: URL(string: urlString)!)
let data = (body as NSString).data(using: String.Encoding.utf8.rawValue)
request.httpBody = data
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers()
alamoFire.request(request).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(JSON)
case .failure(let error):
failure(responseObject, error)
}
}
请指点我的方向,如何将httpbody与Alamofire 4相关联
答案 0 :(得分:11)
在Alamofire 4.0中,您应该使用ParameterEncoding
协议。这是一个示例,它使任何String
UTF8
可编码。
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
答案 1 :(得分:11)
试试这个方法?
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseObject(completionHandler: { (response : DataResponse<T>) in
})