Created
September 18, 2024 17:03
-
-
Save cshireman/932ec1781ef654d988e741e28e86f4e4 to your computer and use it in GitHub Desktop.
A task based data source that makes a JSON request to an API endpoint
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
// | |
// BasicDataSource.swift | |
// ShireWorkout | |
// | |
// Created by Chris Shireman on 9/18/24. | |
// | |
import Foundation | |
import UIKit | |
class BasicDataSource { | |
let baseURL: String | |
init(baseURL: String) { | |
self.baseURL = baseURL | |
} | |
func get<T: Codable>(completion: @escaping (T?, Error?) -> Void) { | |
guard let url = URL(string: baseURL + "/endpoint") else { | |
completion(nil, "Invalid URL") | |
return | |
} | |
let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, response, error in | |
guard let data = data else { | |
if let error = error { | |
completion(nil, error) | |
} else { | |
completion(nil, "No data in response") | |
} | |
return | |
} | |
do { | |
let decoder = JSONDecoder() | |
let result = try decoder.decode(T.self, from: data) | |
completion(result, nil) | |
} catch { | |
completion(nil, error) | |
return | |
} | |
} | |
task.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment