class func fetchTodos(completionHandler: (Result<[Todo], NSError>) -> Void) {
let todosEndpoint: String = "http://jsonplaceholder.typicode.com/todos/"
Alamofire.request(.GET, todosEndpoint)
.responseJSON { response in
// check for errors, tell caller if needed
guard response.result.error == nil else {
completionHandler(.Failure(response.result.error!))
return
}
// make sure we got data & it's valid JSON
guard let value = response.result.value else {
let failureReason = "Could not get or serialize JSON for Todos"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
completionHandler(.Failure(error))
return
}
// Make sure the JSON is an array, like we expect (and not a dictioanry)
guard let jsonTodosArray = value as? [[String: AnyObject]] else {
let failureReason = "Todos not parsed as expected array"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
completionHandler(.Failure(error))
return
}
// Turn the JSON array into an array of Swift objects
// assumes we have a Todo class with an initializer that takes a jsonArray
let todosArray = jsonTodosArray.flatMap { Todo(jsonArray: $0) }
// hand the array of Todos back to the caller
completionHandler(.Success(todosArray))
}
}