diff options
author | Nicholas Tay <nick@windblume.net> | 2022-03-20 01:54:36 +1100 |
---|---|---|
committer | Nicholas Tay <nick@windblume.net> | 2022-03-20 01:54:36 +1100 |
commit | 72cb5b0afef7fe861db5f8e30064478fa05f7025 (patch) | |
tree | 4efc3ba852962a24a4e6408d284a1dbe69beefbf /foray/ForayNetworkManager.swift | |
parent | e37397519e44f546adf550ab4c11e39eeefe252d (diff) | |
download | forayios-72cb5b0afef7fe861db5f8e30064478fa05f7025.tar.gz forayios-72cb5b0afef7fe861db5f8e30064478fa05f7025.tar.bz2 forayios-72cb5b0afef7fe861db5f8e30064478fa05f7025.zip |
Split structs into other file, split networking out
It isn't much so far, as it is just effectively the API retrieval
function extracted from the TableViewController. But this should also
allow other VCs to get from API too if required :^)
Diffstat (limited to '')
-rw-r--r-- | foray/ForayNetworkManager.swift | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/foray/ForayNetworkManager.swift b/foray/ForayNetworkManager.swift new file mode 100644 index 0000000..ab1e2b5 --- /dev/null +++ b/foray/ForayNetworkManager.swift @@ -0,0 +1,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() + } +} |