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)
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。