gpt4 book ai didi

Swift 4 使用 Alamofire 和 Codable 编写发布请求

转载 作者:行者123 更新时间:2023-11-28 07:35:38 25 4
gpt4 key购买 nike

我正在尝试通过 Alamofire 发送带有 Codable 模型的发布请求。我应该把我编码的数据放在哪里?提前感谢您的帮助。

这是我要发送的模型

final class Score: Codable {
var id: Int?
var name: String
var level: Int
var userID: Int


init(
id: Int? = nil, name: String, level: Int, userID: Int) {
self.id = id
self.name = name
self.level = level
self.userID = userID
}


convenience init() {
self.init(name: "", level: 0, userID: 0)

}

这里是发送函数。

 @IBAction func postWithAF(_ sender: Any) {

let anotherScore = Score()
anotherScore.level = 5
anotherScore.name = "Syd Luckenbach"
anotherScore.userID = 3

let jsonData = try encoder.encode(anotherScore)

let headers: HTTPHeaders = [
"Content-Type": "application/json"
]


Alamofire.request("http://192.168.1.5:8080/json/\(anotherScore)/addScore", method: .post, headers: headers, encoding: JSONEncoding.default).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result

if let json = response.result.value {
print("JSON: \(json)") // serialized json response
self.textView.text = "JSON: \(json)"
}

if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string

self.textView.text.append(" Data: \(utf8Text)")
}
}

}

最佳答案

在通过 Alamofire 发送请求之前创建 URLRequest。尝试示例代码:

var request = URLRequest(url: "http://192.168.1.5:8080/json/\(anotherScore)/addScore")!
request.setValue("application/json", "Content-Type")
request.httpMethod = .post
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in

print(response)
}

关于Swift 4 使用 Alamofire 和 Codable 编写发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235646/

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