Skip to content

Instantly share code, notes, and snippets.

@vyder
Last active September 13, 2024 16:17
Show Gist options
  • Save vyder/4d5567cf1c72463fd8af31b2ac6f0828 to your computer and use it in GitHub Desktop.
Save vyder/4d5567cf1c72463fd8af31b2ac6f0828 to your computer and use it in GitHub Desktop.
//
// NetworkClient.swift
//
// Created by Vidur Murali on 11/12/23.
//
import Foundation
class NetworkClient {
static func get<T: Decodable>(_ url: URL) async -> T? {
let urlRequest = URLRequest(url: url)
var data: Data
var response: URLResponse
var result: T?
do {
(data, response) = try await URLSession.shared.data(for: urlRequest)
guard(response as? HTTPURLResponse)?.statusCode == 200 else {
fatalError("Error Fetching Data")
}
do {
result = try JSONDecoder().decode(T.self, from: data)
} catch {
print("Error")
}
} catch {
print("Error")
}
return result
}
static func post<T: Decodable, D: Encodable>(_ url: URL, body: D) async throws -> T? {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
let requestBody = try JSONEncoder().encode(body)
urlRequest.httpBody = requestBody
let (data, response) = try await URLSession.shared.data(for: urlRequest)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
let result = try JSONDecoder().decode(T.self, from: data)
return result
} catch {
print("Error: \(error.localizedDescription)")
throw error
}
}
}
let url = URL(string: "http://endpoint.com/blah/blah/resource")
// GET
let result: [Todo]? = await NetworkClient.get(url!)
// POST
let todo = Todo("Buy milk")
do {
let result: Todo? = try await NetworkClient.post(url!, todo)
} catch {
print("Error")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment