Skip to content

Instantly share code, notes, and snippets.

@ekscrypto
Created February 21, 2019 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekscrypto/668f173ab07454c0273423abd15519fb to your computer and use it in GitHub Desktop.
Save ekscrypto/668f173ab07454c0273423abd15519fb to your computer and use it in GitHub Desktop.
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