Created
May 1, 2019 12:51
-
-
Save cupnoodle/4aa4021fc339448caaccb28b0af3fed6 to your computer and use it in GitHub Desktop.
Call URLSession downloadTask sequentially
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
//: [Previous](@previous) | |
import Foundation | |
//: [Next](@next) | |
class URLSessionOperation : Operation { | |
var task : URLSessionDownloadTask? | |
enum OperationState : Int { | |
case ready | |
case executing | |
case finished | |
} | |
var state : OperationState = .ready | |
override var isReady: Bool { return state == .ready } | |
override var isExecuting: Bool { return state == .executing } | |
override var isFinished: Bool { return state == .finished } | |
init(session: URLSession, downloadTaskURL: URL, completionHandler: ((URL?, URLResponse?, Error?) -> Void)?) { | |
super.init() | |
task = session.downloadTask(with: downloadTaskURL, completionHandler: { [weak self] (localURL, response, error) in | |
if let self = self { | |
if let completionHandler = completionHandler { | |
completionHandler(localURL, response, error) | |
} | |
self.willChangeValue(forKey: "isFinished") | |
self.willChangeValue(forKey: "isExecuting") | |
self.state = .finished | |
if let error = error { | |
print("error fetching \(downloadTaskURL.absoluteString), \(error.localizedDescription)") | |
} else { | |
print("finished fetching \(downloadTaskURL.absoluteString)") | |
} | |
self.didChangeValue(forKey: "isFinished") | |
self.didChangeValue(forKey: "isExecuting") | |
} | |
}) | |
} | |
override func start() { | |
if(self.isCancelled) { | |
self.willChangeValue(forKey: "isFinished") | |
state = .finished | |
self.didChangeValue(forKey: "isFinished") | |
return | |
} | |
self.willChangeValue(forKey: "isExecuting") | |
self.task?.resume() | |
state = .executing | |
self.didChangeValue(forKey: "isExecuting") | |
} | |
override func cancel() { | |
super.cancel() | |
self.task?.cancel() | |
} | |
} | |
let queue = OperationQueue() | |
queue.maxConcurrentOperationCount = 1 | |
var urls = [ | |
URL(string: "https://github.com/fluffyes/AppStoreCard/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/DispatchQueue/archive/master.zip")!, | |
URL(string: "https://github.com/fluffyes/telegrammy/archive/master.zip")! | |
] | |
for url in urls { | |
let operation = URLSessionOperation(session: URLSession.shared, downloadTaskURL: url, completionHandler: { (localURL, urlResponse, error) in | |
}) | |
queue.addOperation(operation) | |
} | |
queue.cancelAllOperations() | |
queue.waitUntilAllOperationsAreFinished() | |
print("finished fetching all") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment