Last active
April 17, 2019 15:04
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
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