16

I'm pretty new to swift and i tried to make a post request to a website, but couldn't come up with an working result, yet. All examples I found didn't work for me either.

I need to send a json body to https://mypostrequestdestination.com/api/

The json body only contains of one value

{State:1}

And the Header has to contain

{"Authorization": bearer "token"}

{"Accept":"application/json"}

{"Content-Type":"application/json"}

Hope someone can help me.

Thanks!

Mason
  • 523
  • 1
  • 4
  • 10

1 Answers1

34

This one worked for me

let token = "here is the token"
let url = URL(string: "https://mypostrequestdestination.com/api/")!

// prepare json data
let json: [String: Any] = ["State": 1]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()
Mason
  • 523
  • 1
  • 4
  • 10