Created
January 2, 2020 10:00
-
-
Save dgyesbreghs/6551b164deaabac1286e1bfb0d04cbf0 to your computer and use it in GitHub Desktop.
This file contains 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
// | |
// HttpCache.swift | |
// Cache | |
// | |
// Created by Dylan Gyesbreghs on 31/12/2019. | |
// Copyright © 2019 Pitch-IT. All rights reserved. | |
// | |
import Foundation | |
public enum HttpCacheStatusCode { | |
case disabled | |
case notModified | |
case modified | |
} | |
public enum HttpCacheHeaderFields: String { | |
case RequestNoneMatch = "If-None-Match" | |
case ResponseNoneMatch = "Etag" | |
} | |
public class HttpCache { | |
private let cache: URLCache = URLCache.shared | |
public func setup(request: inout URLRequest) { | |
/// Make sure we have a cached response for that request. | |
if let cachedResponse = cache.cachedResponse(for: request), | |
let httpResponse = cachedResponse.response as? HTTPURLResponse, | |
let value = httpResponse.allHeaderFields[HttpCacheHeaderFields.ResponseNoneMatch.rawValue] as? String { | |
request.addValue(value, forHTTPHeaderField: HttpCacheHeaderFields.RequestNoneMatch.rawValue) | |
} | |
} | |
public func save(response: URLResponse, data: Data, request: URLRequest) -> HttpCacheStatusCode { | |
if let httpResponse = response as? HTTPURLResponse { | |
/// | |
/// If Response is not modified, don't do anything. | |
/// | |
if httpResponse.statusCode == HttpStatusCode.notModified.rawValue { | |
return .notModified | |
} | |
/// | |
/// Check if a ETag Header is available | |
/// | |
if let _ = httpResponse.allHeaderFields[HttpCacheHeaderFields.ResponseNoneMatch.rawValue] { | |
cache.storeCachedResponse(CachedURLResponse(response: response, data: data), for: request) | |
return .modified | |
} | |
} | |
return .disabled | |
} | |
public func cachedResponse(request: URLRequest) -> CachedURLResponse? { | |
return cache.cachedResponse(for: request) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment