Skip to content

Instantly share code, notes, and snippets.

@niamster
Created January 7, 2022 01:29
Show Gist options
  • Save niamster/96451eeb68fe3057186c5b7fd70409cf to your computer and use it in GitHub Desktop.
Save niamster/96451eeb68fe3057186c5b7fd70409cf to your computer and use it in GitHub Desktop.
Test request caching when requesting GH notifications
import Foundation
func fetch(cachePolicy: URLRequest.CachePolicy) {
let apiToken = ProcessInfo.processInfo.environment["GITHUB_API_TOKEN"]!
var request = URLRequest(url: URL(string: "https://api.github.com/notifications?all=false&participating=true")!, cachePolicy: cachePolicy)
request.addValue("token \(apiToken)", forHTTPHeaderField: "Authorization")
request.addValue("no-cache", forHTTPHeaderField: "Cache-Control")
URLSession.shared.dataTask(with: request) { _, response, _ in
guard let httpResponse = response as? HTTPURLResponse else { return }
let headers = httpResponse.allHeaderFields
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(df.string(from: Date()), "Cache-Control:", headers["Cache-Control"]!, "Etag:", headers["Etag"] ?? "?", "Date:", headers["Date"]!)
}.resume()
}
fetch(cachePolicy: .useProtocolCachePolicy)
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
fetch(cachePolicy: .useProtocolCachePolicy)
}
RunLoop.current.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment