Swift 4 написать запрос на пост с Alamofire и Codable - PullRequest
0 голосов
/ 10 ноября 2018

Я пытаюсь отправить почтовый запрос с моделью Codable через Alamofire. Где я могу вставить данные, которые я закодировал? Заранее спасибо за помощь.

Вот моя модель, которую я отправляю

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 голосов
/ 10 ноября 2018

Создайте URLRequest перед отправкой запроса через Alamofire. Попробуйте пример кода:

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)
   }
...