Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Last active January 29, 2019 11:25
Show Gist options
  • Save charlieInDen/13dc2475bff7d4856f5e7b7651f4c73b to your computer and use it in GitHub Desktop.
Save charlieInDen/13dc2475bff7d4856f5e7b7651f4c73b to your computer and use it in GitHub Desktop.
Restructuring code for Create URLSession Task and make request to server and parse the data , It will help in writing Integration test cases
class APIRequestLoader<T: APIRequest> {
let apiRequest: T
let urlSession: URLSession
init(apiRequest: T, urlSession: URLSession = .shared) {
self.apiRequest = apiRequest
self.urlSession = urlSession
}
func loadAPIRequest(requestData: T.RequestDataType,
completionHandler: @escaping (T.ResponseDataType?, Error?) -> Void) {
do {
let urlRequest = try apiRequest.makeRequest(from: requestData)
urlSession.dataTask(with: urlRequest) { data, response, error in
guard let data = data else { return completionHandler(nil, error) }
do {
let parsedResponse = try self.apiRequest.parseResponse(data: data)
completionHandler(parsedResponse, nil)
} catch {
completionHandler(nil, error)
}
}.resume()
}catch { return completionHandler(nil, error) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment