Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save therabbitwindfall/67ffc2b7a9dafeea8df1ffa504b703fd to your computer and use it in GitHub Desktop.

Select an option

Save therabbitwindfall/67ffc2b7a9dafeea8df1ffa504b703fd to your computer and use it in GitHub Desktop.
Ordered Downloading
var filesToBeDownloaded : [URL]()
func fillURLs(){
// Набиваем массив URL-ами
filesToBeDownloaded.append( ... )
// Стартуем загрузку
downloadNext()
}
func downloadNext(){
// Если массив не пустой - начинаем качать
if filesToBeDownloaded.count > 0 {
// вырезаем первый элемент и начинаем качать по его URL
let nextFile = filesToBeDownloaded.removeFirst()
// когда скачали - запускаем downloadNext снова
_ = FileDownloader(sourceFile:fileNext, completion: downloadNext)
} else {
// Если очередь загрузки пуста - сообщаем юзеру, что все скачано
DispatchQueue.main.async {
let alert = UIAlertController(title: "", message: "Files downloaded!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
currentViewController?.present(alert, animated: true, completion: nil)
}
}
}
/*
FileDownloader
*/
class FileDownloader {
init(sourceFile:URL, completion:@escaping()->Void) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:sourceFile!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Тут я делаю обработку скачанного контента
// Вызываем Callback на завершение скачивания
completion()
}
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment