
Using URLSession for network requests in Swift allows you to interact with web services and fetch data asynchronously. Here’s a basic guide on how to use URLSession for making network requests:
- Create URLSession Instance: Begin by creating a URLSession instance. You can use either a shared session or create a custom session based on your requirements.
let session = URLSession.shared
Create URL and URLRequest: Define the URL for the API endpoint you want to interact with and create a URLRequest object with the URL. Optionally, you can configure the request further with additional properties such as HTTP method, headers, and body.
if let url = URL(string: "https://api.example.com/data") {
var request = URLRequest(url: url)
request.httpMethod = "GET" // or "POST", "PUT", etc.
// Configure additional request properties if needed
}
Create Data Task: Use the URLSession instance to create a data task with the URLRequest. This task will handle the network request asynchronously.
let task = session.dataTask(with: request) { data, response, error in
// Handle response and error
if let error = error {
// Handle error
print("Error: \(error.localizedDescription)")
return
}
guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
// Handle invalid response
print("Invalid response")
return
}
if let data = data {
// Parse and process the received data
// Example: Decode JSON data
do {
let decodedData = try JSONDecoder().decode(MyModel.self, from: data)
// Process decoded data
} catch {
// Handle decoding error
print("Decoding error: \(error)")
}
}
}
Resume Data Task: After creating the data task, call the resume()
method to start the network request.
task.resume()
- Handle Response: Inside the completion handler of the data task, handle the response data, HTTP status codes, and any errors that occur during the network request.
- If
data
is notnil
, process the received data (e.g., JSON parsing). - Check the HTTP status code to ensure the request was successful (e.g., status code
200
for success). - Handle any errors that occurred during the request.
- If