Skip to content

Instantly share code, notes, and snippets.

@cshireman
Created September 18, 2024 16:46
Show Gist options
  • Save cshireman/bd236a0aaa58dd962838c5d269216bb7 to your computer and use it in GitHub Desktop.
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
//
// 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