Skip to content

Instantly share code, notes, and snippets.

@bharathreddys77
Last active May 23, 2021 08:02
Show Gist options
  • Save bharathreddys77/757681a069add6252ffd5f47744c6588 to your computer and use it in GitHub Desktop.
Save bharathreddys77/757681a069add6252ffd5f47744c6588 to your computer and use it in GitHub Desktop.
ServiceController triggers API and fetch data. This file implements NteworkController protocol
// Possible request types
private enum ServiceType:String {
case GET
case POST
case PUT
case DELETE
case PATCH
}
struct ServiceController:NetworkingController {
func loginUser(request:LoginRequest,completion:@escaping(_ result:Result<LoginResponse,NetworkControllerError>) -> Void) {
networkRequestResult(urlString: "Login URL", type: .POST, header: nil, encodingData: request, completion: completion)
}
func forgotPassword(request:ForgotPasswordRequest,completion:@escaping(_ result:Result<ForgotPwdResponse,NetworkControllerError>) -> Void) {
networkRequestResult(urlString: "URL", type: .POST, header: nil, encodingData: request, completion: completion)
}
}
extension ServiceController {
private func networkRequestResult<Q:Encodable,T:Decodable>(urlString:String,type:ServiceType,header:[String:Any]?,encodingData input:Q?,completion:@escaping(Result<T,NetworkError>,Any?) -> Void) {
guard Reachability.isConnectedToNetwork() else {
completion(.failure(NetworkControllerError.NoNetworkError),nil)
return URLSession(configuration: URLSessionConfiguration.default)
}
guard let url = URL(string: Constants.BASE_URL+urlString) else {
completion(.failure(NetworkControllerError.BadURLError),nil)
return URLSession(configuration: URLSessionConfiguration.default)
}
let config = URLSessionConfiguration.default
var urlSession = URLSession(configuration:config)
if let _ = header {
config.httpAdditionalHeaders = header!
urlSession = URLSession(configuration: config)
}
var request = URLRequest(url: url)
request.httpMethod = type.rawValue
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("*/*", forHTTPHeaderField: "Accept")
if let body = input,type == .POST {
do {
request.httpBody = try JSONEncoder().encode(body)
} catch {
print("unable to encode input data \(error)")
}
}
urlSession.dataTask(with: request) { (responseData, urlResponse, urlError) in
guard urlError == nil else {
DispatchQueue.main.async { completion(.failure(NetworkControllerError.customError(message: urlError?.localizedDescription ?? "")),nil) }
return
}
if let response = urlResponse,response is HTTPURLResponse {
guard let data = responseData else {
DispatchQueue.main.async { completion(.failure(NetworkControllerError.NoDataAvailableInResponseError),nil)
}
return
}
print("status code \((response as! HTTPURLResponse).statusCode)")
if (response as! HTTPURLResponse).statusCode != 200 {
DispatchQueue.main.async {
do{
let values:NetworkError = try JSONDecoder().decode(NetworkError.self, from: data)
completion(.failure(NetworkControllerError.Non200StatusCodeError(values)),nil)
}catch{
completion(.failure(NetworkControllerError.NoDataAvailableInResponseError),nil)
}
}
} else {
do {
let values = try JSONDecoder().decode(T.self, from: data)
print("decoded data \(values)")
DispatchQueue.main.async { completion(.success(values),nil )}
} catch {
print("POST API Response parse error \(error)")
DispatchQueue.main.async {
completion(.failure(NetworkControllerError.UnParsableError),nil)
}
}
}
} else {
print("UnknownError")
DispatchQueue.main.async { completion(.failure(NetworkControllerError.UnknownError),nil) }
}
}.resume()
return urlSession
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment