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

时间:2018-11-10 02:57:28

标签: swift swift4 alamofire

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

}

1 个答案:

答案 0 :(得分:0)

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