Skip to content

Instantly share code, notes, and snippets.

@ChrisLawther
Last active May 28, 2019 16:21
Show Gist options
  • Save ChrisLawther/9b20e0159b35c6037add476f2700132d to your computer and use it in GitHub Desktop.
Save ChrisLawther/9b20e0159b35c6037add476f2700132d to your computer and use it in GitHub Desktop.
// 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