Last active
January 29, 2019 11:25
-
-
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
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
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