aboutsummaryrefslogtreecommitdiff
path: root/foray/ForayNetworkManager.swift
blob: ab1e2b597e27b033202282a7108a0ed8bb0f93bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
//  ForayNetworkManager.swift
//  foray
//
//  Created by Nicholas Tay on 20/3/2022.
//

import Foundation

class ForayNetworkManager {
    static let shared = ForayNetworkManager()
    
    var basicUsername: String? = nil
    var basicPassword: String? = nil
    
    // Reuse JSON decoder, allows for customisation of things like date decode if required
    var jsonDecoder: JSONDecoder = {
        let jd = JSONDecoder()
        // Defaults to year-month-date format
        jd.dateDecodingStrategy = .custom({ (decoder) -> Date in
            let container = try decoder.singleValueContainer()
            let dateStr = try container.decode(String.self)
            
            let dateFormat = DateFormatter()
            dateFormat.dateFormat = "yyyy-MM-dd"
            
            return dateFormat.date(from: dateStr)!
        })
        return jd
    }()
    
    func get<T: Decodable>(url: String,
                           onComplete: @escaping ([T]) -> ()) {
        var request = URLRequest(url: URL(string: url)!)
        request.cachePolicy = .reloadRevalidatingCacheData // Needed otherwise default caching policy seems not to check properly
        
        // Basic auth if required
        if (basicUsername != nil && basicPassword != nil) {
            let authData = (basicUsername! + ":" + basicPassword!).data(using: .utf8)!.base64EncodedString()
            request.addValue("Basic \(authData)", forHTTPHeaderField: "Authorization")
        }

        URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
            let items = try! self.jsonDecoder.decode([T].self, from: data!)
            
            // Possibly passing back to UI, need to do it on the main thread (I think due to async?)
            DispatchQueue.main.async { onComplete(items) }
        }).resume()
    }
}