Last active
March 13, 2019 15:20
-
-
Save jemai/cb289b96c9cc2e179d7631e5b13b1a64 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 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