Created
September 18, 2024 16:46
-
-
Save cshireman/bd236a0aaa58dd962838c5d269216bb7 to your computer and use it in GitHub Desktop.
My code to make a JSON request and process the response using AsyncAwait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// AsyncDataSource.swift | |
// ShireWorkout | |
// | |
// Created by Chris Shireman on 9/18/24. | |
// | |
import Foundation | |
class AsyncDataSource { | |
let baseURL: String | |
init(baseURL: String) { | |
self.baseURL = baseURL | |
} | |
func get<T: Codable>() async throws -> T { | |
guard let url = URL(string: baseURL+"/endpoint") else { throw "Invalid URL" } | |
let (data, _) = try await URLSession.shared.data(from: url) | |
let decoder = JSONDecoder() | |
let result = try decoder.decode(T.self, from: data) | |
return result.result | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment