ios 如何在 Swift 中使用 NSURLSession downloadTask 顺序下载多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32322386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Download Multiple Files Sequentially using NSURLSession downloadTask in Swift
提问by CraigH
I have an app that has to download multiple large files. I want it to download each file one by one sequentially instead of concurrently. When it runs concurrently the app gets overloaded and crashes.
我有一个必须下载多个大文件的应用程序。我希望它按顺序而不是同时下载每个文件。当它同时运行时,应用程序会过载并崩溃。
So. Im trying to wrap a downloadTaskWithURL inside a NSBlockOperation and then setting the maxConcurrentOperationCount = 1 on the queue. I wrote this code below but it didnt work since both files get downloaded concurrently.
所以。我试图将 downloadTaskWithURL 包装在 NSBlockOperation 中,然后在队列上设置 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)
}
}
How can write this properly to achieve my goal of only download one file at a time.
如何正确编写它以实现我一次只下载一个文件的目标。
回答by Rob
Your code won't work because URLSessionDownloadTask
runs asynchronously. Thus the BlockOperation
completes before the download is done and therefore while the operations fire off sequentially, the download tasks will continue asynchronously and in parallel.
您的代码将无法URLSessionDownloadTask
运行,因为异步运行。因此在BlockOperation
下载完成之前完成,因此当操作顺序触发时,下载任务将异步并行地继续。
To address this, you can wrap the requests in asynchronous Operation
subclass. See Configuring Operations for Concurrent Executionin the Concurrency Programming Guidefor more information.
为了解决这个问题,您可以将请求包装在异步Operation
子类中。有关更多信息,请参阅并发编程指南中的为并发执行配置操作。
But before I illustrate how to do this in your situation (the delegate-based URLSession
), let me first show you the simpler solution when using the completion handler rendition. We'll later build upon this for your more complicated question. So, in Swift 3 and later:
但在我说明如何在您的情况下(基于委托的URLSession
)执行此操作之前,让我首先向您展示使用完成处理程序呈现时的更简单的解决方案。我们稍后会在此基础上解决您更复杂的问题。因此,在 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.finish() }
guard
let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode
else {
// handle invalid return codes however you'd like
return
}
guard let temporaryURL = temporaryURL, error == nil else {
print(error ?? "Unknown 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()
}
}
Where
在哪里
/// Asynchronous operation base class
///
/// This is abstract to class emits all of the necessary KVO notifications 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 `finish()` is called; or
/// override `cancel` method, calling `super.cancel()` and then cleaning-up
/// and ensuring `finish()` is called.
class AsynchronousOperation: Operation {
/// State for this operation.
@objc private enum OperationState: Int {
case ready
case executing
case finished
}
/// Concurrent queue for synchronizing access to `state`.
private let stateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".rw.state", attributes: .concurrent)
/// Private backing stored property for `state`.
private var rawState: OperationState = .ready
/// The state of the operation
@objc private dynamic var state: OperationState {
get { return stateQueue.sync { rawState } }
set { stateQueue.sync(flags: .barrier) { rawState = newValue } }
}
// MARK: - Various `Operation` properties
open override var isReady: Bool { return state == .ready && super.isReady }
public final override var isExecuting: Bool { return state == .executing }
public final override var isFinished: Bool { return state == .finished }
// KVO for dependent properties
open override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
if ["isReady", "isFinished", "isExecuting"].contains(key) {
return [#keyPath(state)]
}
return super.keyPathsForValuesAffectingValue(forKey: key)
}
// Start
public final override func start() {
if isCancelled {
finish()
return
}
state = .executing
main()
}
/// Subclasses must implement this to perform their work and they must not call `super`. The default implementation of this function throws an exception.
open override func main() {
fatalError("Subclasses must implement `main`.")
}
/// Call this function to finish an operation that is currently executing
public final func finish() {
if !isFinished { state = .finished }
}
}
Then you can do:
然后你可以这样做:
for url in urls {
queue.addOperation(DownloadOperation(session: session, url: url))
}
So that's one very easy way to wrap asynchronous URLSession
/NSURLSession
requests in asynchronous Operation
/NSOperation
subclass. More generally, this is a useful pattern, using AsynchronousOperation
to wrap up some asynchronous task in an Operation
/NSOperation
object.
所以这是在异步/子类中包装异步URLSession
/NSURLSession
请求的一种非常简单的方法。更一般地说,这是一种有用的模式,用于在/对象中包装一些异步任务。Operation
NSOperation
AsynchronousOperation
Operation
NSOperation
Unfortunately, in your question, you wanted to use delegate-based URLSession
/NSURLSession
so you could monitor the progress of the downloads. This is more complicated.
不幸的是,在您的问题中,您想使用基于委托的URLSession
/NSURLSession
以便您可以监控下载进度。这个比较复杂。
This is because the "task complete" NSURLSession
delegate methods are called at the session object's delegate. This is an infuriating design feature of NSURLSession
(but Apple did it to simplify background sessions, which isn't relevant here, but we're stuck with that design limitation).
这是因为NSURLSession
在会话对象的委托中调用了“任务完成”委托方法。这是一个令人恼火的设计功能NSURLSession
(但 Apple 这样做是为了简化后台会话,这与此处无关,但我们坚持该设计限制)。
But we have to asynchronously complete the operations as the tasks finish. So we need some way for the session to figure out which operation to complete when didCompleteWithError
is called. Now you could have each operation have its own NSURLSession
object, but it turns out that this is pretty inefficient.
但是我们必须在任务完成时异步完成操作。因此,我们需要某种方式让会话确定在didCompleteWithError
调用时要完成哪个操作。现在你可以让每个操作都有自己的NSURLSession
对象,但事实证明这是非常低效的。
So, to handle that, I maintain a dictionary, keyed by the task's taskIdentifier
, which identifies the appropriate operation. That way, when the download finishes, you can "complete" the correct asynchronous operation. Thus:
因此,为了处理这个问题,我维护了一个字典,以任务的 为键taskIdentifier
,它标识了适当的操作。这样,当下载完成时,您可以“完成”正确的异步操作。因此:
/// 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 OperationQueue 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 `URLSession` 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 queueDownload(_ 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) {
guard
let httpResponse = downloadTask.response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode
else {
// handle invalid return codes however you'd like
return
}
do {
let manager = FileManager.default
let destinationURL = try manager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent)
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: URLSessionTaskDelegate methods
extension DownloadOperation: URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
defer { finish() }
if let error = error {
print(error)
return
}
// do whatever you want upon success
}
}
And then use it like so:
然后像这样使用它:
let downloadManager = DownloadManager()
override func viewDidLoad() {
super.viewDidLoad()
let urlStrings = [
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg"
]
let urls = urlStrings.compactMap { URL(string: 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()
}
}
) }
let completion = BlockOperation {
print("all done")
}
for url in urls {
let operation = downloadManager.queueDownload(url)
completion.addDependency(operation)
}
OperationQueue.main.addOperation(completion)
}
See revision historyfor Swift 2 implementation.
查看Swift 2 实现的修订历史。
回答by user3567929
Here is rather minimalistic and pure-swift approach. With no NSOperationQueue(), just didSet-observer
这是相当简约和纯粹的方法。没有 NSOperationQueue(),只是 didSet-observer
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://blog.medium.com/39-reasons-we-wont-soon-forget-2016-154ac95683af#.cmb37i58b",
"https://backchannel.com/in-2017-your-coworkers-will-live-everywhere-ae14979b5255#.wmi6hxk9p"]
}
}
In ViewController:
在视图控制器中:
import UIKit
import Foundation
private let _sharedUpdateStatus = UpdateStatus()
class UpdateStatus : NSObject {
// MARK: - SHARED INSTANCE
class var shared : UpdateStatus {
return _sharedUpdateStatus
}
var indexDownloaded = 0
}
回答by Yunus T.
More than one code in the background situation. I can learn by used global variable and NSTimer. You can try too.
后台情况不止一个代码。我可以通过使用的全局变量和 NSTimer 来学习。你也可以试试。
Define 'indexDownloaded' global variable.
定义“indexDownloaded”全局变量。
print("??" + URL.lastPathComponent! + " downloaded")
UpdateStatus.shared.indexDownloaded += 1
print(String(UpdateStatus.shared.indexDownloaded) + "\" + String(UpdateStatus.shared.count))
This code add in the DownloadOperation class.
此代码添加到 DownloadOperation 类中。
func startTimeAction () {
let urlStrings = [
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg",
"http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg"
]
let urls = urlStrings.flatMap { URL(string: [operation2 addDependency:operation1]
) }
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)
}
This function in your viewController.
这个函数在你的 viewController 中。
##代码##in this way, by updating the progressview will look at the number of downloaded each time the timer runs.
这样,通过更新进度视图,每次计时器运行时都会查看下载的数量。
回答by Destiny
Objective-C version is:
Objective-C 版本是:
##代码##