0

I'm just learning Web APIs with Swift. And I've done as follows

Make some basic configuration

let session = URLSession(configuration: .default)

// Prepare URL  #the URL is virtual now
let url = URL(string: "http://something.com/api")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"

Set Post parameter

let parameters: [String: String] = [
    "user_ID": "1",
]

let jsonData = try JSONEncoder().encode(parameters)

request.httpBody = jsonData

Take request to our web api

// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    // Check for Error
    if let error = error {
        print("Error took place \(error)")
        return
    }
    guard let data = data else { return }

    do {
        let myEnterprise = try JSONDecoder().decode(Enterprise.self, from: data)

        print("Response data:\n \(myEnterprise)")
        print("Response data:\n \(myEnterprise.returnData)")
    } catch let jsonErr {
        print(jsonErr)
    }
}

task.resume()

myEnterprise is always nil. Can anyone help me?

Majster
  • 3,611
  • 5
  • 38
  • 60
  • Does this answer your question? [The resource could not be loaded because the App Transport Security policy requires the use of a secure connection](https://stackoverflow.com/questions/32631184/the-resource-could-not-be-loaded-because-the-app-transport-security-policy-requi) – Chris Apr 24 '20 at 13:33
  • You might also need `Content-Type: application/json`. request.setValue("application/json", forHTTPHeaderField: "Content-Type") – Botond Magyarosi Apr 24 '20 at 13:49

0 Answers0