Last active
May 28, 2019 16:21
-
-
Save ChrisLawther/9b20e0159b35c6037add476f2700132d to your computer and use it in GitHub Desktop.
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
// Prompted by an article here: https://fluffy.es/download-files-sequentially/ | |
// ... an alternative, lighter-weight approach to ensuring asynchronous downloads happen sequentially | |
let urls = [ | |
URL(string: "https://github.com/fluffyes/AppStoreCard/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/currentLocation/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/DispatchQueue/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/dynamicFont/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/telegrammy/archive/master.zip")! | |
] | |
func downloadSequentially(_ urls: [URL], completion: @escaping (URL?, URLResponse?, Error?) -> Void) { | |
// Queues are automatically retained until all operations are completed | |
// (see https://developer.apple.com/documentation/foundation/operationqueue) | |
let queue = OperationQueue() | |
queue.maxConcurrentOperationCount = 1 | |
for url in urls { | |
queue.addOperation { | |
let semaphore = DispatchSemaphore(value: 0) | |
URLSession.shared.downloadTask(with: url, completionHandler: { (tempURL, response, error) in | |
completion(tempURL, response, error) | |
semaphore.signal() | |
}).resume() | |
semaphore.wait() | |
} | |
} | |
} | |
downloadSequentially(urls) { (tempUrl, response, error) -> Void in | |
print("Downloaded to: \(tempUrl)") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment