4️⃣URLSession

Fall 2023 | Vin Bui

In the previous sections, we used Alamofire to send network requests. Although Alamofire is very elegant and simple to use, there are times when we want to use native Swift to send network requests. We can do this with URLSession.

GET Requests

Let’s take a look at the Alamofire version from the previous section:

// 1. Create the function
func fetchRoster(completion: @escaping ([Member]) -> Void) {
    // 2. Specify the endpoint
    let endpoint = "<Enter URL String Here>"
    
    // 3. Create a decoder
    let decoder = JSONDecoder()
    // decoder.dateDecodingStrategy = .iso8601 // Only if needed
    // decoder.keyDecodingStrategy = .convertFromSnakeCase // Only if needed
    
    // 4. Create the request
    AF.request(endpoint, method: .get)
        .validate()
        .responseDecodable(of: [Member].self, decoder: decoder) { response in
	    // 5. Handle the response
            switch response.result {
            case .success(let members):
                print("Successfully fetched \(members.count) members")
                completion(members)
            case .failure(let error):
                print("Error in NetworkManager.fetchRoster: \(error)")
            }
        }
}

We can do the same exact thing using URLSession (only steps after Step 3 are different):

POST Requests

Let’s take a look at a POST request using Alamofire:

If we were to use URLSession, we need to:

  • Change the httpMethod property of the URLRequest to "POST".

  • Call the setValue function with ("application/json", forHTTPHeaderField: "Content-Type").

  • Set the httpBody property of the URLRequest.

    • The code below uses JSONSerialization to serialize the dictionary parameters to JSON and use it as the request body.

    • Alternatively, we can also use a JSONEncoder to encode our object into JSON, but it won’t be shown here.

Note that we do not have to create the decoder inside of the function call. We can create a JSONDecoder object and store it as a property in our NetworkManager class to be used for all functions. The same can be applied to the endpoint variable containing a String value of our endpoint.

Last updated

Was this helpful?