每次下载包含一个文件的数据点的多个文件

时间:2017-04-20 13:45:56

标签: swift

此代码在下载一个文件时效果很好。但是,当尝试下载包含数据的多个文件并缓存传入的数据时会导致混乱。由于下载不间断发生,因此一个文件完成,下一个文件启动。我无法缓存它们,因为我不知道哪些数据属于哪个文件。

lazy var downloadQueue: OperationQueue = {

    var queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1000000
    queue.name = "Files"
    return queue
}()

func fetch(url: String, completionHandler: @escaping ([String:String]) -> (), completionHandlerQueue: OperationQueue?) {

let task = session.dataTask(with: URL(string: url)!, completionHandler: {
        (data, response, error) in

        guard let data = data, let type = String(data: data, encoding: String.Encoding.utf8), error == nil else {

            print("Error with the data: \(error.debugDescription)")
            return
        }

        guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {

            return
        }

        guard completionHandlerQueue != nil else {
            return
        }
        completionHandlerQueue!.addOperation(BlockOperation(block: {
                completionHandler(type)
            }))
    })
    task.resume()
}

//这是链接

let urls = [.....]

func start() {
    for url in urls {
       print("Start")         
       fetch(url: url, completionHandler: { type in

            // The incoming data I don't know which belongs to which url.
       }, completionHandlerQueue: downloadQueue)
    }
    print("End")
}

由于它的异步我会得到

Start

End

然后数据将会到来。我怎么能克服这个?

0 个答案:

没有答案