gpt4 book ai didi

swift - Alamofire 设置带有数据的请求正文

转载 作者:行者123 更新时间:2023-11-28 11:40:10 27 4
gpt4 key购买 nike

在 objC 中我这样做:

NSData *postData = ...
NSMutableURLRequest *request = ...
[request setHTTPBody:postData];

在 Swift Alamofire 中如何做?

Alamofire.request(url, method: .post, parameters: nil, encoding: URLEncoding.default, headers: headers)
request.validate().responseJSON {
...
}

最佳答案

Alamfire 接受[String:Any]

 do {
let params = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
Alamofire.request(url, method: .post, parameters:params, encoding: JSONEncoding.default, headers: headers)
request.validate().responseJSON {
...
}
}
catch {
print(error)
}

swift 4.2

Alamofire.request(url, method: .post, parameters: [:], encoding: "test", headers: [:])  

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
}

}

关于swift - Alamofire 设置带有数据的请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com