Skip to content

Instantly share code, notes, and snippets.

@mhijack
Last active April 7, 2021 06:00
Show Gist options
  • Save mhijack/0e4fb4259a585f7dff4c1399045da2e5 to your computer and use it in GitHub Desktop.
Save mhijack/0e4fb4259a585f7dff4c1399045da2e5 to your computer and use it in GitHub Desktop.
func getUsers(complete: @escaping (_ success: Bool, _ users: [User]?, _ error: Error?) -> ()) -> Request {
return alamoFireManager
.request("https://myserver.com/",
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: nil)
.validate(statusCode: 200..<500)
.responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let data):
switch response.response?.statusCode {
case 200, 204:
/// Handle success, parse JSON data
do {
let users = try JSONDecoder().decode([Users].self, from: JSONSerialization.data(withJSONObject: data))
complete(true, users, nil)
} catch let error {
/// Handle json decode error
complete(false, nil, Error())
}
case 429:
/// Handle 429 error
complete(false, nil, Error(code: 429))
default:
/// Handle unknown error
complete(false, nil, Error(code: -1))
}
case .failure(let error):
/// Handle request failure
complete(false, nil, Error(code: 0))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment