Skip to content

Instantly share code, notes, and snippets.

@keehun
Last active April 17, 2019 15:04
Show Gist options
  • Save keehun/f20b113193280c527f0fcd4358f849ae to your computer and use it in GitHub Desktop.
Save keehun/f20b113193280c527f0fcd4358f849ae to your computer and use it in GitHub Desktop.
func getMoviePackage(for movieID: String, completion: MoviePackageFetchCompletion? = nil) {
var movieURL: URL?
var subtitleURL: URL?
var movieFile: File?
var subtitleFile: File?
/// The `DispatchGroup` for the parallel URL fetch operations
let urlFetchGroup = DispatchGroup()
urlFetchGroup.enter()
service.getURL(for: movieID, type: .movie) { result, error in
guard error == nil else {
urlFetchGroup.leave()
return
}
guard let url = result.url else {
urlFetchgroup.leave()
return
}
movieURL = url
urlFetchGroup.leave()
}
urlFetchGroup.enter()
service.getURL(for: movieID, type: .subtitle) { result, error in
guard error == nil else {
urlFetchGroup.leave()
return
}
guard let url = result.url else {
urlFetchgroup.leave()
return
}
subtitleURL = url
urlFetchGroup.leave()
}
/// Commence downloading when URL fetch has finished for both
/// types.
urlFetchGroup.notify(queue: .main) {
/// Exit early and trigger callback with error if either of
/// the URLs are nil.
guard let theMovieURL = movieURL,
let theSubtitleURL = subtitleURL else {
completion(nil, .serviceError)
return
}
/// If both URLs are not nil, continue onto the download phase
let downloadGroup = DispatchGroup()
/// ... repeat with downloading files ...
downloadGroup.notify(queue: .main) {
guard let movie = movieFile,
let subtitle = subtitleFile
else {
completion(nil, .serviceError)
return
}
completion(MoviePackage(movie: movie, subtitle: subtitle),
nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment