From 1adbed9f8b94521befd237c14d36325a55037a41 Mon Sep 17 00:00:00 2001 From: Nicholas Tay Date: Sun, 17 Jul 2022 02:13:04 +1000 Subject: Experiment with async/await Note that URLSession async only works >=iOS 15. I changed the target for now, but may mess with continuations. --- foray/Fetchers/ForayFetcher.swift | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) (limited to 'foray/Fetchers') diff --git a/foray/Fetchers/ForayFetcher.swift b/foray/Fetchers/ForayFetcher.swift index d8df037..e4c6fd9 100644 --- a/foray/Fetchers/ForayFetcher.swift +++ b/foray/Fetchers/ForayFetcher.swift @@ -27,23 +27,18 @@ class ForayFetcher { 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") - } + func fetch(url: String) async throws -> T { + var request = URLRequest(url: URL(string: url)!) + request.cachePolicy = .reloadRevalidatingCacheData // Needed otherwise default caching policy seems not to check properly - URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in - let items = try! self.jsonDecoder.decode(T.self, from: data!) - receiver(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") } + + let (data, _) = try await URLSession.shared.data(for: request) + let items = try jsonDecoder.decode(T.self, from: data) + return items } } -- cgit