aboutsummaryrefslogtreecommitdiff
path: root/foray/Fetchers/ForayFetcher.swift
diff options
context:
space:
mode:
authorNicholas Tay <nick@windblume.net>2022-07-17 02:13:04 +1000
committerNicholas Tay <nick@windblume.net>2022-07-17 02:13:16 +1000
commit1adbed9f8b94521befd237c14d36325a55037a41 (patch)
tree91d81b4740514083010c72f5f0559283ccd849fa /foray/Fetchers/ForayFetcher.swift
parentdaee1f1b5c739f42ba54a1ebbb9655f5034e315f (diff)
downloadforayios-1adbed9f8b94521befd237c14d36325a55037a41.tar.gz
forayios-1adbed9f8b94521befd237c14d36325a55037a41.tar.bz2
forayios-1adbed9f8b94521befd237c14d36325a55037a41.zip
Experiment with async/await
Note that URLSession async only works >=iOS 15. I changed the target for now, but may mess with continuations.
Diffstat (limited to '')
-rw-r--r--foray/Fetchers/ForayFetcher.swift27
1 files changed, 11 insertions, 16 deletions
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<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")
- }
+ func fetch<T: Decodable>(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
}
}