Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@trupin
Last active September 23, 2018 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trupin/35a9768677c817b1c9a52d7c40be4a63 to your computer and use it in GitHub Desktop.
Save trupin/35a9768677c817b1c9a52d7c40be4a63 to your computer and use it in GitHub Desktop.
final class MovieManager {
func getDiscoverMovies(_ completion: @escaping (Page<Movie>?) -> Void) {
let completionOnMainThread = { result in
DispatchQueue.main.async {
completion(result)
}
}
guard let url = URL(string: "https://api.themoviedb.org/3/discover/movie?api_key=1a6eb1225335bbb37278527537d28a5d") else {
completion(nil)
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
completionOnMainThread(nil)
return
}
guard let response = response as? HTTPURLResponse else {
completionOnMainThread(nil)
return
}
guard response.statusCode == 200 || response.statusCode == 304 else {
completionOnMainThread(nil)
return
}
guard let data = data else {
completionOnMainThread(nil)
return
}
do {
let model = try JSONDecoder().decode(Page<Movie>.self, from: data)
completionOnMainThread(model)
} catch {
completionOnMainThread(nil)
}
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment