Last active
October 18, 2023 13:21
-
-
Save jkereako/a38f782a33996215f0dfdcdff2465797 to your computer and use it in GitHub Desktop.
Networking
This file contains hidden or 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
import Foundation | |
public enum HTTPMethod: String { | |
case get = "GET" | |
case post = "POST" | |
case put = "PUT" | |
case delete = "DELETE" | |
} | |
public enum NetworkError: Error { | |
case noData | |
case notFound | |
case serverError | |
case unknownError | |
} | |
public final class NetworkClient { | |
private let urlSession: URLSession | |
public init(urlSession: URLSession = URLSession(configuration: .default)) { | |
self.urlSession = urlSession | |
} | |
public func makeRequest(to url: URL, | |
method httpMethod: HTTPMethod, | |
body: Data? = nil, | |
headers: [String: String] = [:], | |
completionHandler: @escaping (Result<Data, Error>) -> Void) { | |
let mutableRequest = NSMutableURLRequest(url: url) | |
// Set the http method | |
mutableRequest.httpMethod = httpMethod.rawValue | |
// `httpBody` *must* be the last property that we set because of this bug: https://bugs.swift.org/browse/SR-6687 | |
mutableRequest.httpBody = body | |
setHeaders(headers, for: mutableRequest) | |
let task = urlSession.dataTask(with: url) { (data: Data?, | |
response: URLResponse?, | |
error: Error?) in | |
guard let httpResponse = response as? HTTPURLResponse else { | |
completionHandler(.failure(NetworkError.notFound)) | |
return | |
} | |
guard let responseData = data else { | |
completionHandler(.failure(NetworkError.noData)) | |
return | |
} | |
// Handle the response | |
switch httpResponse.statusCode { | |
// Success! Now try to decode the response | |
case 200...399: | |
completionHandler(.success(responseData)) | |
// Client error | |
case 400...499: | |
completionHandler(.failure(NetworkError.notFound)) | |
// Server error | |
case 500...599: | |
completionHandler(.failure(NetworkError.serverError)) | |
default: | |
// This should never happen. | |
assertionFailure("Unexpected response code.") | |
completionHandler(.failure(NetworkError.unknownError)) | |
} | |
} | |
task.resume() | |
} | |
private func setHeaders(_ headers: [String: String], for request: NSMutableURLRequest) { | |
let standardHeaders = [ | |
"Accept": "application/json", | |
"Accept-Charset": "UTF-8", | |
"Accept-Encoding": "gzip" | |
] | |
standardHeaders.forEach { request.setValue($1, forHTTPHeaderField: $0) } | |
headers.forEach { request.setValue($1, forHTTPHeaderField: $0) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Network Client
This is a very simple networking API. I use it for small programs and interviews.