WIP
This commit is contained in:
57
Werkout_ios/Network/Network.swift
Normal file
57
Werkout_ios/Network/Network.swift
Normal file
@@ -0,0 +1,57 @@
|
||||
//
|
||||
// Network.swift
|
||||
// Werkout_ios
|
||||
//
|
||||
// Created by Trey Tartt on 6/19/23.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum FetchableError: Error {
|
||||
case apiError(Error)
|
||||
case noData
|
||||
case decodeError(Error)
|
||||
case endOfFileError
|
||||
}
|
||||
|
||||
protocol Fetchable {
|
||||
associatedtype Response: Codable
|
||||
|
||||
var baseURL: String { get }
|
||||
var endPoint: String { get }
|
||||
|
||||
func fetch(completion: @escaping (Result<Response, FetchableError>) -> Void)
|
||||
}
|
||||
|
||||
extension Fetchable {
|
||||
var baseURL: String {
|
||||
"http://127.0.0.1:8000/"
|
||||
}
|
||||
|
||||
func fetch(completion: @escaping (Result<Response, FetchableError>) -> Void) {
|
||||
let url = URL(string: baseURL+endPoint)!
|
||||
|
||||
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
|
||||
if let error = error {
|
||||
completion(.failure(.apiError(error)))
|
||||
return
|
||||
}
|
||||
guard let data = data else {
|
||||
completion(.failure(.noData))
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let model = try JSONDecoder().decode(Response.self, from: data)
|
||||
completion(.success(model))
|
||||
return
|
||||
} catch {
|
||||
completion(.failure(.decodeError(error)))
|
||||
return
|
||||
}
|
||||
completion(.failure(.endOfFileError))
|
||||
})
|
||||
|
||||
task.resume()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user