iOS HTTP

Making a Request

  • URLComponents - appending query string params
  • URLRequest - request info
  • URLSession - creates tasks, saves common config for them
  • URLSessionTask - runs HTTP requests
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://example.com")
let request = URLRequest(url: url)
let task = session.dataTask(with: request) {
    (data, response, error) in
    
    if let jsonData = data {
        if let jsonString = String(data: jsonData,
                                   encoding: .utf8) {
            print(jsonString)
        } else if let requestError = error {
            print("Error fetching interesting photos: \(requestError)")
        } else {
            print("Unexpected error with the request")
        }
    }
}
task.resume()

Serializing/Deserializing JSON