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
httpMethodproperty of theURLRequestto"POST".Call the
setValuefunction with("application/json", forHTTPHeaderField: "Content-Type").Set the
httpBodyproperty of theURLRequest.The code below uses
JSONSerializationto serialize the dictionaryparametersto JSON and use it as the request body.Alternatively, we can also use a
JSONEncoderto encode our object into JSON, but it wonβt be shown here.
Last updated
Was this helpful?