Created
July 4, 2017 12:25
-
-
Save therabbitwindfall/67ffc2b7a9dafeea8df1ffa504b703fd to your computer and use it in GitHub Desktop.
Ordered Downloading
This file contains hidden or 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
| 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