load a request in swift

Here's an example of how to load a request in Swift using URLSession:

main.swift
// create the url request
guard let url = URL(string: "https://example.com/api/someEndpoint") else {
   return
}
var request = URLRequest(url: url)
request.addValue("Bearer someAccessToken", forHTTPHeaderField: "Authorization")

// create the URLSession and request task
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
    // handle the response
    guard let data = data else {
        print("Error: No data returned")
        return
    }

    guard let httpResponse = response as? HTTPURLResponse else {
        print("Error: Invalid response type")
        return
    }

    guard (200...299).contains(httpResponse.statusCode) else {
        print("Error: status code \(httpResponse.statusCode)")
        return
    }

    // do something with the data
}

// start the task
task.resume()
848 chars
32 lines

In this example, we create a URLRequest and add an authorization header. We then create a URLSession and a dataTask with the request. Finally, we handle the response and the data that's returned.

gistlibby LogSnag