OSDN Git Service

列挙子の名称変更
[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     
13     switch status {
14     case 200, 203, 206,
15          301, 304,
16          404, 410:
17         return true
18         
19     default:
20         return false
21     }
22 }
23
24 private func cacheable(response: HTTPURLResponse) -> Bool {
25     
26     guard let cc = response.allHeaderFields["Cache-Control"] as? String,
27         let _ = cc.lowercased().range(of: "no-store")
28         else { return true }
29     
30     return false
31 }
32
33 private func cacheable(request: URLRequest) -> Bool {
34     
35     guard let cc: String = request.allHTTPHeaderFields?["Cache-Control"]
36         else { return true }
37     
38     if let _ = cc.lowercased().range(of: "no-store") { return false }
39     if let _ = cc.lowercased().range(of: "no-cache") { return false }
40     
41     return true
42 }
43
44 private func policy(request: URLRequest) -> URLCache.StoragePolicy {
45     
46     if let scheme = request.url?.scheme?.lowercased(),
47         scheme == "https" {
48         
49         return .allowedInMemoryOnly
50     }
51     
52     return .allowed
53 }
54
55 func cacheStoragePolicy(for request: URLRequest, response: HTTPURLResponse) -> URLCache.StoragePolicy {
56     
57     if cacheable(status: response.statusCode),
58         cacheable(response: response),
59         cacheable(request: request) {
60         
61         return policy(request: request)
62     }
63     
64     return .notAllowed
65 }