Making HTTP requests is an essential skill for any Swift developer. In this lesson, we'll learn how to make both simple and complex HTTP requests, using various APIs, and understanding their responses.
HTTP (Hypertext Transfer Protocol) is the foundation of any data exchange on the web. It allows for communication between a client (like your Swift app) and a server.
Swift provides the URLSession class to handle HTTP requests. Let's start with a simple GET request.
import Foundation
struct APIResponse: Codable {
let data: String
}
let url = URL(string: "https://example.com/api/data")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error)")
return
}
guard let data = data else {
print("No data received")
return
}
do {
let responseObject = try JSONDecoder().decode(APIResponse.self, from: data)
print(responseObject.data)
} catch {
print("Error decoding response: \(error)")
}
}
task.resume()š Note: The APIResponse struct is a simple example of a Swift model that conforms to the Codable protocol, allowing us to decode JSON data easily.
In some cases, you might need to customize your HTTP requests. Here's an example of a custom POST request:
import Foundation
let url = URL(string: "https://example.com/api/data")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonData = """
{
"key": "value"
}
""".data(using: .utf8)!
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Handle response as before
}
task.resume()Handling errors and implementing retries can help ensure your app's HTTP requests are robust and reliable. Here's an example of a function that handles common HTTP errors and retries the request up to a certain limit.
func fetchData(url: URL, maxRetries: Int = 3) {
var task: URLSessionDataTask?
func retry() {
task?.cancel()
task = URLSession.shared.dataTask(with: url) { (data, response, error) in
// Handle response as before
}
task?.resume()
}
let retryCount = maxRetries
task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
if case .networkConnectionLost = error as NSError, retryCount > 0 {
retry()
return
}
print("Error: \(error)")
}
// Handle response as before
}
task?.resume()
}Which HTTP method is used to create a new resource?
Happy coding! š