OSDN Git Service

バージョンを1.9b33に更新
[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") else {
28             
29             return true
30     }
31     
32     return false
33 }
34
35 private func cacheable(request: URLRequest) -> Bool {
36     
37     guard let cc: String = request.allHTTPHeaderFields?["Cache-Control"] else { return true }
38     
39     if let _ = cc.lowercased().range(of: "no-store") { return false }
40     if let _ = cc.lowercased().range(of: "no-cache") { return false }
41     
42     return true
43 }
44
45 private func policy(request: URLRequest) -> URLCache.StoragePolicy {
46     
47     if let scheme = request.url?.scheme?.lowercased(),
48         scheme == "https" {
49         
50         return .allowedInMemoryOnly
51     }
52     
53     return .allowed
54 }
55
56 func cacheStoragePolicy(for request: URLRequest, response: HTTPURLResponse) -> URLCache.StoragePolicy {
57     
58     if cacheable(status: response.statusCode),
59         cacheable(response: response),
60         cacheable(request: request) {
61         
62         return policy(request: request)
63     }
64     
65     return .notAllowed
66 }