Skip to content

Instantly share code, notes, and snippets.

@jemai
Last active March 13, 2019 15:20
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 jemai/cb289b96c9cc2e179d7631e5b13b1a64 to your computer and use it in GitHub Desktop.
Save jemai/cb289b96c9cc2e179d7631e5b13b1a64 to your computer and use it in GitHub Desktop.
extension Requester {
public static func execute<T: Codable>(ofType: T.Type, request : Request,
completion: @escaping
(_ result: HTTPResult<T?,HTTPCallErrorType<Error>?>) -> Void) {
// first we create the URLRequest
if let httpRequest = createRequest(from: request) {
// we use the nativ URL session to exute it
URLSession.shared.dataTask(with: httpRequest) { (data, response, error) in
if let error = error {
// first error to handle when we have a request error
completion(HTTPResult.failure(HTTPCallErrorType.responseError(error)))
} else {
// callback to main thread
DispatchQueue.main.async {
if let data = data {
do {
// trying to map the data to the Generic codable type
let object = try JSONDecoder().decode(T.self, from: data)
completion(HTTPResult.success(object))
return
} catch let error {
// second error to hanle mapping error, data not conform to the object
completion(HTTPResult.failure(HTTPCallErrorType.mappingError(error)))
return
}
}
// error data is nil
completion(HTTPResult.failure(HTTPCallErrorType.dataError))
}
}
}.resume()
} else {
completion(HTTPResult.failure(HTTPCallErrorType.urlError))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment