Created
January 31, 2020 09:46
-
-
Save nitin-agam/af3116f046fbd148d8f7491fe00a7565 to your computer and use it in GitHub Desktop.
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
import Foundation | |
enum NetworkError: Error { | |
case decodingError | |
case domainError | |
case urlError | |
} | |
enum HttpMethod: String { | |
case get = "GET" | |
case post = "POST" | |
} | |
struct Resource<T: Codable> { | |
let url: URL | |
var httpMethod: HttpMethod = .get | |
var body: Data? | |
} | |
class WebService { | |
func load<T>(resource: Resource<T>, completion: @escaping (Result<T, NetworkError>) -> Void) { | |
var request = URLRequest(url: resource.url) | |
request.httpMethod = resource.httpMethod.rawValue | |
request.httpBody = resource.body | |
request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
URLSession.shared.dataTask(with: request) { (data, response, error) in | |
guard let data = data, error == nil else { | |
completion(.failure(.domainError)) | |
return | |
} | |
do { | |
let responseData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) | |
print(responseData) | |
} catch { | |
print("error") | |
} | |
let result = try? JSONDecoder().decode(T.self, from: data) | |
if let result = result { | |
DispatchQueue.main.async { | |
completion(.success(result)) | |
} | |
} else { | |
completion(.failure(.decodingError)) | |
} | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment