Skip to content

Instantly share code, notes, and snippets.

@mhijack
Last active April 7, 2021 06:56
Show Gist options
  • Save mhijack/0cbe42d560debddea788c7fdc81e05a9 to your computer and use it in GitHub Desktop.
Save mhijack/0cbe42d560debddea788c7fdc81e05a9 to your computer and use it in GitHub Desktop.
struct APIError {
let code: Int
let message: String
}
struct UserListAPIResponseData {
let users: [User]
/// This is a list of users, we might have pagination information, thus struct comes in handy in holding that information
}
enum UserListAPIResponse {
case Success(UserListAPIResponseData)
case Fail(APIError) /// Error code, Error message
}
func getUsers(complete: @escaping (UserListAPIResponse) -> ()) -> 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(.Success(UserListAPIResponseData(users: users)))
} catch let error {
/// Handle json decode error
complete(.Fail(APIError(code: -1, message: "we ran into error")))
}
case 429:
/// Handle 429 error
complete(.Fail(APIError(code: 429, message: "we ran into error")))
default:
/// Handle unknown error
complete(.Fail(APIError(code: -1, message: "we ran into error")))
}
case .failure(let error):
/// Handle request failure
complete(.Fail(APIError(code: 0, message: "we ran into error")))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment