我正在尝试用URLSession发送POST API调用,但它没有发送请求集主体。
我的鲟鱼是可编码鲟鱼,APi在邮差工作
这是我的代码
var urlRequest = URLRequest(url: URL(string: EndPoint.BASE_URL + "SignUp")!)
urlRequest.httpMethod = "post"
do {
let requestBody = try JSONEncoder().encode(self)
urlRequest.httpBody = requestBody
urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
} catch let error {
debugPrint(error.localizedDescription)
}
URLSession.shared.dataTask(with: urlRequest) { (data, httpUrlResponse, error) in
if(data != nil && data?.count != 0)
{
guard let data = data else {return }
do
{
let response = try JSONDecoder().decode(SignUpResponse.self, from: data)
completion(.success(response))
}
catch let decodingError {
debugPrint(decodingError.localizedDescription)
}
}
}.resume()
你能看看吗,我缺了什么。
由于您的请求结构继承自可编码类型别名,我认为您所要做的就是替换代码
let requestBody = try JSONEncoder().encode(self)
带有
let requestBody = try JSONEncoder().encode(YOUR_REQUEST_STRUCTURE)
除此之外,这一切看起来都很好,而且作为一种健全性检查,向URLRequest
添加一个调试器,并验证URLRequest
是否生成了与您在邮递员中拥有的URL匹配的正确注册URL。
此外,明智的做法是,除非需要,否则不要将Codable用于您的请求模型,而只实现Encodable protocol