Skip to content

Instantly share code, notes, and snippets.

@twittemb
Created June 2, 2018 18:36
Show Gist options
  • Select an option

  • Save twittemb/b8cb10a053f3c04cd7b445a482385ab9 to your computer and use it in GitHub Desktop.

Select an option

Save twittemb/b8cb10a053f3c04cd7b445a482385ab9 to your computer and use it in GitHub Desktop.
func fetch<Model: Codable> (fromRoute route: Route<Model>, then: @escaping (Result<Model>) -> Void) {
// make sure that the endpoint path is a valid URL
guard let url = URL(string: self.baseURL+route.endpoint) else {
then(.failure(NSError(domain: "warpfactor.io", code: 500)))
return
}
Alamofire
.request(url, method: route.httpMethod)
.responseData { (response) in
guard response.error == nil else {
then(.failure(response.error!))
return
}
if let data = response.data,
let model = try? JSONDecoder().decode(Model.self, from: data) {
then(.success(model))
} else {
then(.failure(NSError(domain: "warpfactor.io", code: 1000, userInfo: ["error":"wrong model"])))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment