From 07a6eb8325d3b67d998003d3fe5ab34e1a72f106 Mon Sep 17 00:00:00 2001 From: Nicholas Tay Date: Fri, 25 Mar 2022 09:52:06 +1100 Subject: getData -> fetch, try threading, move logic around --- foray/ForayNetworkManager.swift | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'foray/ForayNetworkManager.swift') diff --git a/foray/ForayNetworkManager.swift b/foray/ForayNetworkManager.swift index ab1e2b5..53e9554 100644 --- a/foray/ForayNetworkManager.swift +++ b/foray/ForayNetworkManager.swift @@ -29,22 +29,23 @@ class ForayNetworkManager { return jd }() - func get(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!) + 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 - // Possibly passing back to UI, need to do it on the main thread (I think due to async?) - DispatchQueue.main.async { onComplete(items) } - }).resume() + // 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