Created
August 23, 2020 01:24
-
-
Save standinga/b78f7d425ebc624ee099d2d90d7bc31a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
URLCache.shared.removeAllCachedResponses() // start each "experiment" with empty cache | |
let timer = Timer(timeInterval: 1, repeats: true) { _ in | |
fetch(title: "useProtocolCachePolicy", policy: .useProtocolCachePolicy) | |
fetch(title: "returnCacheDataElseLoad", policy: .returnCacheDataElseLoad) | |
fetch(title: "reloadIgnoringLocalCacheData", policy: .reloadIgnoringLocalCacheData) | |
// fetch(title: "returnCacheDataDontLoad", policy: .returnCacheDataDontLoad) | |
} | |
func fetch(title: String, policy: URLRequest.CachePolicy) { | |
// var request = URLRequest(url: URL(string: "http://localhost:3000/\(title)")!) // works ok for all requests | |
var request = URLRequest(url: URL(string: "http://localhost:3000/")!) // works only for one request at a time | |
request.setValue(title, forHTTPHeaderField: "cache-policy") // to log and show which cache-policy was used on the server | |
request.cachePolicy = policy // doesn't matter if it's specified for URLSessionConfiguration, regardless if we hit different enpoints per cache policy or the same endpoint | |
URLSession.shared.dataTask(with: request) { data, response, error in | |
guard let httpResponse = response as? HTTPURLResponse else { return } | |
let headers = httpResponse.allHeaderFields | |
let etag = headers["Etag"] ?? "-" | |
let cc = headers["Cache-Control"] ?? "-" | |
print("\(title) ".prefix(30), String(data: data!, encoding: .utf8)!, "Status Code:", httpResponse.statusCode, "Etag:", etag, "Cache-Control:", cc) | |
}.resume() | |
} | |
RunLoop.current.add(timer, forMode: .common) | |
RunLoop.current.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment