From 1752ea7075939fb49dd72e0b8ea2accc2be1b02a Mon Sep 17 00:00:00 2001 From: Nicholas Tay Date: Fri, 25 Mar 2022 09:59:35 +1100 Subject: Reorganise: NetworkManager -> Fetcher, Models -> dedicated groups --- foray/Fetchers/ForayFetcher.swift | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 foray/Fetchers/ForayFetcher.swift (limited to 'foray/Fetchers') 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(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() + } + } +} -- cgit