How do I handle ETags and conditional requests in Swift?

In Swift, handling ETags and conditional requests is essential for optimizing network communication. ETags (Entity Tags) are part of HTTP headers used for web cache validation. By using ETags, a client can make conditional requests to the server to check if the resource has been modified since it was last accessed.

You can use the URLSession APIs in Swift to manage these requests effectively. Below is an example of how to handle ETags and conditional requests in a Swift application.

import Foundation // Create a URL let url = URL(string: "https://example.com/resource")! var request = URLRequest(url: url) // Set the If-None-Match header with the ETag value let etag = "your-etag-value" // Replace with your actual ETag request.addValue(etag, forHTTPHeaderField: "If-None-Match") let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error)") return } if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 304 { print("Resource not modified, use cached data") // Use cached data } else if httpResponse.statusCode == 200 { print("Resource modified, update cached data") // Process incoming data if let data = data { // Update your cache with new data } } } } task.resume()

conditional requests ETags URLSession Swift networking HTTP cache validation