如何在Swift中使用NSURLSession downloadTask按顺序下载多个文件

我有一个应用程序必须下载多个大文件。 我希望它逐一下载每个文件,而不是同时下载。 当它同时运行的应用程序得到超载和崩溃。

所以。 我试图包装在NSBlockOperation downloadTaskWithURL,然后在队列上设置maxConcurrentOperationCount = 1。 我在下面编写了这个代码,但它没有工作,因为两个文件同时下载。

import UIKit class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. processURLs() } func download(url: NSURL){ let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) let downloadTask = session.downloadTaskWithURL(url) downloadTask.resume() } func processURLs(){ //setup queue and set max conncurrent to 1 var queue = NSOperationQueue() queue.name = "Download queue" queue.maxConcurrentOperationCount = 1 let url = NSURL(string: "http://azspeastus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&sr=b&sig=%2FZNzdvvzwYO%2BQUbrLBQTalz%2F8zByvrUWD%2BDfLmkpZuQ%3D&se=2015-09-01T01%3A48%3A51Z&sp=r") let url2 = NSURL(string: "http://azspwestus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&sr=b&sig=ufnzd4x9h1FKmLsODfnbiszXd4EyMDUJgWhj48QfQ9A%3D&se=2015-09-01T01%3A48%3A51Z&sp=r") let urls = [url, url2] for url in urls { let operation = NSBlockOperation { () -> Void in println("starting download") self.download(url!) } queue.addOperation(operation) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { //code } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { // } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { var progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) println(progress) } } 

如何正确地写这个来实现我一次只下载一个文件的目标。

您的代码将无法正常工作,因为NSURLSessionDownloadTaskasynchronous运行。 因此NSBlockOperation在下载完成之前完成,因此,当操作依次启动时,下载任务将asynchronous并行地继续。

为了解决这个问题,你可以把请求包装在asynchronousNSOperation子类中。 有关更多信息,请参阅并发编程指南中的为并发执行configuration操作 。

但在说明如何在您的情况下(基于委托的NSURLSession )说明如何执行此操作之前,请让我首先向您展示使用完成处理程序呈现的更简单的解决scheme。 我们稍后将在此基础上为您的更复杂的问题进行构build。 所以,在Swift 3:

 class DownloadOperation : AsynchronousOperation { var task: URLSessionTask! init(session: URLSession, url: URL) { super.init() task = session.downloadTask(with: url) { temporaryURL, response, error in defer { self.completeOperation() } guard error == nil && temporaryURL != nil else { print("\(error)") return } do { let manager = FileManager.default let destinationURL = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(url.lastPathComponent) _ = try? manager.removeItem(at: destinationURL) // remove the old one, if any try manager.moveItem(at: temporaryURL!, to: destinationURL) // move new one there } catch let moveError { print("\(moveError)") } } } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } /// Asynchronous operation base class /// /// This is abstract to class performs all of the necessary KVN of `isFinished` and /// `isExecuting` for a concurrent `Operation` subclass. You can subclass this and /// implement asynchronous operations. All you must do is: /// /// - override `main()` with the tasks that initiate the asynchronous task; /// /// - call `completeOperation()` function when the asynchronous task is done; /// /// - optionally, periodically check `self.cancelled` status, performing any clean-up /// necessary and then ensuring that `completeOperation()` is called; or /// override `cancel` method, calling `super.cancel()` and then cleaning-up /// and ensuring `completeOperation()` is called. public class AsynchronousOperation : Operation { override public var isAsynchronous: Bool { return true } private let stateLock = NSLock() private var _executing: Bool = false override private(set) public var isExecuting: Bool { get { return stateLock.withCriticalScope { _executing } } set { willChangeValue(forKey: "isExecuting") stateLock.withCriticalScope { _executing = newValue } didChangeValue(forKey: "isExecuting") } } private var _finished: Bool = false override private(set) public var isFinished: Bool { get { return stateLock.withCriticalScope { _finished } } set { willChangeValue(forKey: "isFinished") stateLock.withCriticalScope { _finished = newValue } didChangeValue(forKey: "isFinished") } } /// Complete the operation /// /// This will result in the appropriate KVN of isFinished and isExecuting public func completeOperation() { if isExecuting { isExecuting = false } if !isFinished { isFinished = true } } override public func start() { if isCancelled { isFinished = true return } isExecuting = true main() } } /* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample's licensing information Abstract: An extension to `NSLock` to simplify executing critical code. From Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/ From https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip */ extension NSLock { /// Perform closure within lock. /// /// An extension to `NSLock` to simplify executing critical code. /// /// - parameter block: The closure to be performed. func withCriticalScope<T>(block: () -> T) -> T { lock() let value = block() unlock() return value } } 

或者在Swift 2中:

 /// Asynchronous NSOperation subclass for downloading class DownloadOperation : AsynchronousOperation { var task: NSURLSessionTask! init(session: NSURLSession, URL: NSURL) { super.init() task = session.downloadTaskWithURL(URL) { temporaryURL, response, error in defer { self.completeOperation() } print(URL.lastPathComponent) guard error == nil && temporaryURL != nil else { print(error) return } do { let manager = NSFileManager.defaultManager() let documents = try manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) let destinationURL = documents.URLByAppendingPathComponent(URL.lastPathComponent!) if manager.fileExistsAtPath(destinationURL.path!) { try manager.removeItemAtURL(destinationURL) } try manager.moveItemAtURL(temporaryURL!, toURL: destinationURL) } catch let moveError { print(moveError) } } } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } // // AsynchronousOperation.swift // // Created by Robert Ryan on 9/20/14. // Copyright (c) 2014 Robert Ryan. All rights reserved. // import Foundation /// Asynchronous Operation base class /// /// This class performs all of the necessary KVN of `isFinished` and /// `isExecuting` for a concurrent `NSOperation` subclass. So, to developer /// a concurrent NSOperation subclass, you instead subclass this class which: /// /// - must override `main()` with the tasks that initiate the asynchronous task; /// /// - must call `completeOperation()` function when the asynchronous task is done; /// /// - optionally, periodically check `self.cancelled` status, performing any clean-up /// necessary and then ensuring that `completeOperation()` is called; or /// override `cancel` method, calling `super.cancel()` and then cleaning-up /// and ensuring `completeOperation()` is called. public class AsynchronousOperation : NSOperation { override public var asynchronous: Bool { return true } private let stateLock = NSLock() private var _executing: Bool = false override private(set) public var executing: Bool { get { return stateLock.withCriticalScope { _executing } } set { willChangeValueForKey("isExecuting") stateLock.withCriticalScope { _executing = newValue } didChangeValueForKey("isExecuting") } } private var _finished: Bool = false override private(set) public var finished: Bool { get { return stateLock.withCriticalScope { _finished } } set { willChangeValueForKey("isFinished") stateLock.withCriticalScope { _finished = newValue } didChangeValueForKey("isFinished") } } /// Complete the operation /// /// This will result in the appropriate KVN of isFinished and isExecuting public func completeOperation() { if executing { executing = false } if !finished { finished = true } } override public func start() { if cancelled { finished = true return } executing = true main() } override public func main() { fatalError("subclasses must override `main`") } } /* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample's licensing information Abstract: An extension to `NSLock` to simplify executing critical code. From Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/ From https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip */ import Foundation extension NSLock { /// Perform closure within lock. /// /// An extension to `NSLock` to simplify executing critical code. /// /// - parameter block: The closure to be performed. func withCriticalScope<T>(@noescape block: Void -> T) -> T { lock() let value = block() unlock() return value } } 

那你可以这样做:

 for url in urls { queue.addOperation(DownloadOperation(session: session, url: url)) } 

所以这是在asynchronousOperation / NSOperation子类中包装asynchronousURLSession / NSURLSession请求的一种非常简单的方法。 更一般地说,这是一个有用的模式,使用AsynchronousOperation来包装Operation / NSOperation对象中的一些asynchronous任务。

不幸的是,在你的问题中,你想使用基于委托的URLSession / NSURLSession所以你可以监视下载的进度。 这更复杂。

这是因为“任务完成” NSURLSession委托方法在会话对象的委托中被调用。 这是NSURLSession一个令人生气的devise特性(但苹果公司做了简化后台会话,这在这里是不相关的,但我们坚持这种devise限制)。

但是,随着任务的完成,我们必须asynchronous地完成操作。 所以我们需要一些方法让会话在调用didCompleteWithError时候完成操作。 现在你可以让每个操作都有自己的NSURLSession对象,但事实certificate这是非常低效的。

所以,为了处理这个问题,我维护一个字典,由任务的taskIdentifier来标识,它标识了相应的操作。 这样,下载完成后,可以“完成”正确的asynchronous操作。 所以,在Swift 3:

 /// Manager of asynchronous download `Operation` objects class DownloadManager: NSObject { /// Dictionary of operations, keyed by the `taskIdentifier` of the `URLSessionTask` fileprivate var operations = [Int: DownloadOperation]() /// Serial NSOperationQueue for downloads private let queue: OperationQueue = { let _queue = OperationQueue() _queue.name = "download" _queue.maxConcurrentOperationCount = 1 // I'd usually use values like 3 or 4 for performance reasons, but OP asked about downloading one at a time return _queue }() /// Delegate-based NSURLSession for DownloadManager lazy var session: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) }() /// Add download /// /// - parameter URL: The URL of the file to be downloaded /// /// - returns: The DownloadOperation of the operation that was queued @discardableResult func addDownload(_ url: URL) -> DownloadOperation { let operation = DownloadOperation(session: session, url: url) operations[operation.task.taskIdentifier] = operation queue.addOperation(operation) return operation } /// Cancel all queued operations func cancelAll() { queue.cancelAllOperations() } } // MARK: URLSessionDownloadDelegate methods extension DownloadManager: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } } // MARK: URLSessionTaskDelegate methods extension DownloadManager: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { let key = task.taskIdentifier operations[key]?.urlSession(session, task: task, didCompleteWithError: error) operations.removeValue(forKey: key) } } /// Asynchronous Operation subclass for downloading class DownloadOperation : AsynchronousOperation { let task: URLSessionTask init(session: URLSession, url: URL) { task = session.downloadTask(with: url) super.init() } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } // MARK: NSURLSessionDownloadDelegate methods extension DownloadOperation: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { do { let manager = FileManager.default let destinationURL = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent) if manager.fileExists(atPath: destinationURL.path) { try manager.removeItem(at: destinationURL) } try manager.moveItem(at: location, to: destinationURL) } catch { print("\(error)") } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) print("\(downloadTask.originalRequest!.url!.absoluteString) \(progress)") } } // MARK: NSURLSessionTaskDelegate methods extension DownloadOperation: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { completeOperation() if error != nil { print("\(error)") } } } 

或者在Swift 2中:

 /// Manager of asynchronous NSOperation objects class DownloadManager: NSObject, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate { /// Dictionary of operations, keyed by the `taskIdentifier` of the `NSURLSessionTask` private var operations = [Int: DownloadOperation]() /// Serial NSOperationQueue for downloads let queue: NSOperationQueue = { let _queue = NSOperationQueue() _queue.name = "download" _queue.maxConcurrentOperationCount = 1 return _queue }() /// Delegate-based NSURLSession for DownloadManager lazy var session: NSURLSession = { let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() return NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) }() /// Add download /// /// - parameter URL: The URL of the file to be downloaded /// /// - returns: The DownloadOperation of the operation that was queued func addDownload(url: NSURL) -> DownloadOperation { let operation = DownloadOperation(session: session, URL: url) operations[operation.task.taskIdentifier] = operation queue.addOperation(operation) return operation } /// Cancel all queued operations func cancelAll() { queue.cancelAllOperations() } // MARK: NSURLSessionDownloadDelegate methods func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { operations[downloadTask.taskIdentifier]?.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { operations[downloadTask.taskIdentifier]?.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } // MARK: NSURLSessionTaskDelegate methods func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { let key = task.taskIdentifier operations[key]?.URLSession(session, task: task, didCompleteWithError: error) operations.removeValueForKey(key) } } /// Asynchronous NSOperation subclass for downloading class DownloadOperation : AsynchronousOperation { let task: NSURLSessionTask init(session: NSURLSession, URL: NSURL) { task = session.downloadTaskWithURL(URL) super.init() } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } // MARK: NSURLSessionDownloadDelegate methods func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { do { let manager = NSFileManager.defaultManager() let documents = try manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) let destinationURL = documents.URLByAppendingPathComponent(downloadTask.originalRequest!.URL!.lastPathComponent!) if manager.fileExistsAtPath(destinationURL.path!) { try manager.removeItemAtURL(destinationURL) } try manager.moveItemAtURL(location, toURL: destinationURL) } catch { print(error) } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) print("\(downloadTask.originalRequest!.URL!.absoluteString) \(progress)") } // MARK: NSURLSessionTaskDelegate methods func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { completeOperation() if error != nil { print(error) } } } 

然后我使用它:

 let downloadManager = DownloadManager() override func viewDidLoad() { super.viewDidLoad() let urlStrings = [ "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/s72-55482.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo10/hires/as10-34-5162.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo-soyuz/apollo-soyuz/hires/s75-33375.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-134-20380.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-140-21497.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-148-22727.jpg" ] let urls = urlStrings.flatMap { URL(string: $0) } // use NSURL in Swift 2 for url in urls { downloadManager.addDownload(url) } } 

这是相当简约和纯粹的方法。 没有NSOperationQueue(),只是没有Set-observer

  import Foundation class DownloadManager { var delegate: HavingWebView? var gotFirstAndEnough = true var finalURL: NSURL?{ didSet{ if finalURL != nil { if let s = self.contentOfURL{ self.delegate?.webView.loadHTMLString(s, baseURL: nil) } } } } var lastRequestBeginning: NSDate? var myLinks = [String](){ didSet{ self.handledLink = self.myLinks.count } } var contentOfURL: String? var handledLink = 0 { didSet{ if handledLink == 0 { self.finalURL = nil print("🔴🔶🔴🔶🔶🔴🔶🔴🔶🔴🔶🔴") } else { if self.finalURL == nil { if let nextURL = NSURL(string: self.myLinks[self.handledLink-1]) { self.loadAsync(nextURL) } } } } } func loadAsync(url: NSURL) { let sessionConfig = NSURLSessionConfiguration.ephemeralSessionConfiguration() let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 15.0) request.HTTPMethod = "GET" print("🚀") self.lastRequestBeginning = NSDate() print("Requet began: \(self.lastRequestBeginning )") let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in if (error == nil) { if let response = response as? NSHTTPURLResponse { print("\(response)") if response.statusCode == 200 { if let content = String(data: data!, encoding: NSUTF8StringEncoding) { self.contentOfURL = content } self.finalURL = url } } } else { print("Failure: \(error!.localizedDescription)"); } let elapsed = NSDate().timeIntervalSinceDate(self.lastRequestBeginning!) print("trying \(url) takes \(elapsed)") print("🏁 Request finished") print("____________________________________________") self.handledLink -= 1 }) task.resume() } } 

在ViewController中:

 protocol HavingWebView { var webView: UIWebView! {get set} } class ViewController: UIViewController, HavingWebView { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let dm = DownloadManager() dm.delegate = self dm.myLinks = ["https://medium.com/the-mission/consider-the-present-and-future-value-of-your-decisions-b20fb72f5e#.a12uiiz11", "https://medium.com/@prianka.kariat/ios-10-notifications-with-attachments-and-much-more-169a7405ddaf#.svymi6230", "https://myerotica.com/jingle-bell-fuck-the-twins-5a48782bf5f1#.mjqz821yo", "https://blog.medium.com/39-reasons-we-wont-soon-forget-2016-154ac95683af#.cmb37i58b", "https://backchannel.com/in-2017-your-coworkers-will-live-everywhere-ae14979b5255#.wmi6hxk9p"] } } 

不止一个代码在后台的情况。 我可以通过使用全局variables和NSTimer来学习。 你也可以试试

定义'indexDownloaded'全局variables。

 import UIKit import Foundation private let _sharedUpdateStatus = UpdateStatus() class UpdateStatus : NSObject { // MARK: - SHARED INSTANCE class var shared : UpdateStatus { return _sharedUpdateStatus } var indexDownloaded = 0 } 

此代码添加在DownloadOperation类中。

 print("⬇️" + URL.lastPathComponent! + " downloaded") UpdateStatus.shared.indexDownloaded += 1 print(String(UpdateStatus.shared.indexDownloaded) + "\\" + String(UpdateStatus.shared.count)) 

这个函数在你的viewController中。

 func startTimeAction () { let urlStrings = [ "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/s72-55482.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo10/hires/as10-34-5162.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo-soyuz/apollo-soyuz/hires/s75-33375.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-134-20380.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-140-21497.jpg", "http://spaceflight.nasa.gov/galleryhttp://img.dovov.comapollo/apollo17/hires/as17-148-22727.jpg" ] let urls = urlStrings.flatMap { URL(string: $0) } for url in urls { queue.addOperation(DownloadOperation(session: session, url: url)) } UpdateStatus.shared.count = urls.count progressView.setProgress(0.0, animated: false) timer.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true) } func timeAction() { if UpdateStatus.shared.count != 0 { let set: Float = Float(UpdateStatus.shared.indexDownloaded) / Float(UpdateStatus.shared.count) progressView.setProgress(set, animated: true) } 

通过这种方式,通过更新progressview将会看每次定时器运行下载的次数。

Objective-C版本是:

 [operation2 addDependency:operation1]