Created
February 21, 2019 01:16
-
-
Save ekscrypto/668f173ab07454c0273423abd15519fb 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
extension APIRequest { | |
public static func post<R: Codable & APIEndpoint, T: Codable, E: Codable>( | |
request: R, | |
onSuccess: @escaping ((_: T) -> Void), | |
onError: @escaping ((_: E?, _: Error) -> Void)) { | |
guard var endpointRequest = self.urlRequest(from: request) else { | |
onError(nil, APIError.invalidEndpoint) | |
return | |
} | |
endpointRequest.httpMethod = "POST" | |
endpointRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
do { | |
endpointRequest.httpBody = try JSONEncoder().encode(request) | |
} catch { | |
onError(nil, error) | |
return | |
} | |
URLSession.shared.dataTask( | |
with: endpointRequest, | |
completionHandler: { (data, urlResponse, error) in | |
DispatchQueue.main.async { | |
self.processResponse(data, urlResponse, error, onSuccess: onSuccess, onError: onError) | |
} | |
}).resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment