Created
April 25, 2018 01:05
-
-
Save trupin/145ec11a40e3f814399c8c802e225f51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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