OSDN Git Service

UAをVersion/10.0.3 Safari/602.4.8に変更
[kcd/KCD.git] / KCD / CacheStoragePolicy.swift
1 //
2 //  CacheStoragePolicy.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/11.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
11 private func cacheable(status: Int) -> Bool {
12     switch status {
13     case 200, 203, 206,
14          301, 304,
15          404, 410:
16         return true
17     default:
18         return false
19     }
20 }
21
22 private func cacheable(response: HTTPURLResponse) -> Bool {
23     guard let cc = response.allHeaderFields["Cache-Control"] as? String,
24         let _ = cc.lowercased().range(of: "no-store")
25         else { return true }
26     return false
27 }
28
29 private func cacheable(request: URLRequest) -> Bool {
30     guard let cc: String = request.allHTTPHeaderFields?["Cache-Control"]
31         else { return true }
32     if let _ = cc.lowercased().range(of: "no-store") { return false }
33     if let _ = cc.lowercased().range(of: "no-cache") { return false }
34     return true
35 }
36
37 private func policy(request: URLRequest) -> URLCache.StoragePolicy {
38     if let scheme = request.url?.scheme?.lowercased(),
39         scheme == "https" {
40         return .allowedInMemoryOnly
41     }
42     return .allowed
43 }
44
45 func CacheStoragePolicy(for request: URLRequest, response: HTTPURLResponse) -> URLCache.StoragePolicy {
46     if cacheable(status: response.statusCode),
47         cacheable(response: response),
48         cacheable(request: request) {
49         return policy(request: request)
50     }
51     return .notAllowed
52 }