Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
final class MovieManager {
/// Fetches popular movies from the server, then stores them.
func getPopularMovies(_ completion: @escaping (Result<[Movie], MovieManagerError>) -> Void) {
HTTPClient.shared.get(path: "/movies/popular") { httpResponse, data, error in
// handles error if any
do {
// parses data from the server
let movies = try JSONDecoder().decode([Movie].self, from: data)
// saves movies in core data
let moc = // instanciate a managed object context...
for movie in movies {
ManagedMovie(movie).createOrUpdateIfExists(in: moc)
}
do {
try moc.save()
} catch {
completion(.failure(.coreData(error)))
return
}
completion(.success(movies))
} catch {
completion(.failure(.parsing(error)))
}
}
}
/// Fetches a movie from the store if it exists, from the server otherwise.
func getMovie(id movieID: String, completion: @escaping (Result<Movie, MovieManagerError>) -> Void) {
let moc = // instanciates a managed object context...
let storedMovieFetch = NSFetchRequest(entityName: "Movie")
storedMovieFetch.predicate = NSPredicate(format: "id == %@", movieID)
do {
// get potential stored movie
guard let storedMovies = try moc.executeFetchRequest(storedMovieFetch) as? [Movie] else {
completion(.failure(.coreData(.inconsistentTable(entityName: "Movie"))))
return
}
if let storedMovie = storedMovies.first {
completion(.success(Movie(storedMovie)))
}
} catch {
completion(.failure(.coreData(error)))
return
}
HTTPClient.shared.get(path: "/movies/\(movieID)") { httpResponse, data, error in
// handles error if any
do {
// parses data from the server
let movie = try JSONDecoder().decode(Movie.self, from: data)
// saves movie in core data
ManagedMovie(movie).createOrUpdateIfExists(in: moc)
do {
try moc.save()
} catch {
completion(.failure(.coreData(error)))
return
}
completion(.success(movie))
} catch {
completion(.failure(.parsing(error)))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment