【问题标题】:Swift 4 write a post request with Alamofire and CodableSwift 4 使用 Alamofire 和 Codable 编写发布请求
【发布时间】:2019-04-13 14:36:42
【问题描述】:

我正在尝试通过 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)")
            }
        }

}

【问题讨论】:

    标签: swift swift4 alamofire


    【解决方案1】:

    在通过 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)
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多