diff options
author | Nicholas Tay <nick@windblume.net> | 2022-03-25 09:59:35 +1100 |
---|---|---|
committer | Nicholas Tay <nick@windblume.net> | 2022-03-25 09:59:35 +1100 |
commit | 1752ea7075939fb49dd72e0b8ea2accc2be1b02a (patch) | |
tree | 04ad843bc6b05d31cc6524cffe652229e8da0ffd /foray/Fetchers | |
parent | 07a6eb8325d3b67d998003d3fe5ab34e1a72f106 (diff) | |
download | forayios-1752ea7075939fb49dd72e0b8ea2accc2be1b02a.tar.gz forayios-1752ea7075939fb49dd72e0b8ea2accc2be1b02a.tar.bz2 forayios-1752ea7075939fb49dd72e0b8ea2accc2be1b02a.zip |
Reorganise: NetworkManager -> Fetcher, Models -> dedicated groups
Diffstat (limited to 'foray/Fetchers')
-rw-r--r-- | foray/Fetchers/ForayFetcher.swift | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/foray/Fetchers/ForayFetcher.swift b/foray/Fetchers/ForayFetcher.swift new file mode 100644 index 0000000..d8df037 --- /dev/null +++ b/foray/Fetchers/ForayFetcher.swift @@ -0,0 +1,49 @@ +// +// ForayNetworkManager.swift +// foray +// +// Created by Nicholas Tay on 20/3/2022. +// + +import Foundation + +class ForayFetcher { + 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 fetch<T: Decodable>(url: String, + receiver: @escaping (T) -> ()) { + // Fetch on a background thread + DispatchQueue.global(qos: .background).async { + 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 (self.basicUsername != nil && self.basicPassword != nil) { + let authData = (self.basicUsername! + ":" + self.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!) + receiver(items) + }).resume() + } + } +} |