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

前端之家收集整理的这篇文章主要介绍了ios – 如何下载多个文件顺序使用NSURLSession downloadTask在Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个应用程序必须下载多个大文件.我想让它逐个下载每个文件,而不是并发.当它同时运行时,应用程序会重载并崩溃.

所以.我试图将一个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,didResumeAtOffset fileOffset: Int64,expectedTotalBytes: Int64) {
        //
    }

    func URLSession(session: NSURLSession,didWriteData bytesWritten: Int64,totalBytesWritten: Int64,totalBytesExpectedToWrite: Int64) {
        var progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        println(progress)
    }

}

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

解决方法

您的代码将无法正常工作,因为NSURLSessionDownloadTask异步运行.因此,NSBlockOperation在下载完成之前完成,因此在操作顺序触发时,下载任务将以异步方式并行进行.

为了解决这个问题,您可以将请求包装在异步NSOperation子类中.有关更多信息,请参阅并发编程指南中的Configuring Operations for Concurrent Execution.

但是,在我说明如何在您的情况(基于委托的NSURLSession)之前,让我首先向您展示使用完成处理程序转换时更简单的解决方案.我们稍后会为您提出更复杂的问题.所以,在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,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,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))
}

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

不幸的是,在您的问题中,您希望使用基于委托的URLSession / NSURLSession,以便您可以监控下载的进度.这更复杂

这是因为在会话对象的委托中调用了“任务完成”NSURLSession委托方法.这是NSURLSession的一个令人激动的设计功能(但是苹果做了简化后台会话,这在这里是不相关的,但我们坚持设计限制).

但是,随着任务的完成,我们必须异步地完成操作.所以我们需要一些方法解决当didCompleteWithError被调用时用操作来完成.现在你可以让每个操作都有自己的NSURLSession对象,但事实证明这是非常低效的.

所以,为了处理这一点,我维护一个字典,由任务的taskIdentifier键入,它标识适当的操作.这样,当下载完成后,您可以“完成”正确的异步操作.所以,在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,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,totalBytesExpectedToWrite: Int64) {
        operations[downloadTask.taskIdentifier]?.urlSession(session,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,didFinishDownloadingTo location: URL) {
        do {
            let manager = FileManager.default
            let destinationURL = try manager.url(for: .documentDirectory,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,totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("\(downloadTask.originalRequest!.url!.absoluteString) \(progress)")
    }
}

// MARK: NSURLSessionTaskDelegate methods

extension DownloadOperation: URLSessionTaskDelegate {

    func urlSession(_ session: URLSession,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,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,didFinishDownloadingToURL location: NSURL) {
        operations[downloadTask.taskIdentifier]?.URLSession(session,didFinishDownloadingToURL: location)
    }

    func URLSession(session: NSURLSession,totalBytesExpectedToWrite: Int64) {
        operations[downloadTask.taskIdentifier]?.URLSession(session,totalBytesExpectedToWrite: totalBytesExpectedToWrite)
    }

    // MARK: NSURLSessionTaskDelegate methods

    func URLSession(session: NSURLSession,task: NSURLSessionTask,didCompleteWithError error: NSError?) {
        let key = task.taskIdentifier
        operations[key]?.URLSession(session,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,didFinishDownloadingToURL location: NSURL) {
        do {
            let manager = NSFileManager.defaultManager()
            let documents = try manager.URLForDirectory(.DocumentDirectory,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,totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("\(downloadTask.originalRequest!.URL!.absoluteString) \(progress)")
    }

    // MARK: NSURLSessionTaskDelegate methods

    func URLSession(session: NSURLSession,didCompleteWithError error: NSError?) {
        completeOperation()
        if error != nil {
            print(error)
        }
    }

}

然后我就这样使用它:

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.flatMap { URL(string: $0) }   // use NSURL in Swift 2

    for url in urls {
        downloadManager.addDownload(url)
    }

}

猜你在找的iOS相关文章