-
-
Save Pasanpr/261e006c6b2dbc281cc3fb0b36ccd314 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
enum APIError: Error { | |
case requestFailed | |
case jsonConversionFailure | |
case invalidData | |
case responseUnsuccessful | |
case jsonParsingFailure | |
var localizedDescription: String { | |
switch self { | |
case .requestFailed: return "Request Failed" | |
case .invalidData: return "Invalid Data" | |
case .responseUnsuccessful: return "Response Unsuccessful" | |
case .jsonParsingFailure: return "JSON Parsing Failure" | |
case .jsonConversionFailure: return "JSON Conversion Failure" | |
} | |
} | |
} | |
extension APIClient { | |
typealias JSON = [String: AnyObject] | |
typealias JSONTaskCompletionHandler = (JSON?, APIError?) -> Void | |
func jsonTask(with request: URLRequest, completionHandler completion: @escaping JSONTaskCompletionHandler) -> URLSessionDataTask { | |
let task = session.dataTask(with: request) { data, response, error in | |
guard let httpResponse = response as? HTTPURLResponse else { | |
completion(nil, .requestFailed) | |
return | |
} | |
if httpResponse.statusCode == 200 { | |
if let data = data { | |
do { | |
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] | |
completion(json, nil) | |
} catch { | |
completion(nil, .jsonConversionFailure) | |
} | |
} else { | |
completion(nil, .invalidData) | |
} | |
} else { | |
completion(nil, .responseUnsuccessful) | |
} | |
} | |
return task | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment