Swift 4 write a post request with Alamofire and Codable

Viewed 2148

I'm trying to send a post request with a Codable model via Alamofire. Where do I put in the data that I've encoded? Thanks for your help in advance.

Here is my model that I'm sending

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)

}

}

Here is the function to send.

 @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)")
            }
        }

}
2 Answers

Create URLRequest before sending the request via Alamofire. Try the example code:

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

You can achieve this in a single Alamofire line. For your example (with AF 5.x) this would look like

import Alamofire

func sendJSONViaPOSTRequest(data: Score) {
    AF.request(
        "some URL", 
        method: .post, 
        parameters: data, 
        encoder: JSONParameterEncoder.default,
        // (Optionally) any additional headers.  
        // 'Content-Type: application/json' is applied automatically.
        headers: yourHeaders)  
    // Followed by any downstream processing methods here
}
Related