1

我有一个场景,我必须从 url 下载一个 zip 文件,一旦下载完成,我需要以异步方式解压缩它。这里的问题是 FileManager.default.copyItem 需要一些时间,因此我无法立即解压缩文件。以下是下载 zip 文件的代码:

   func saveZipFile(url: URL, directory: String) -> Void {
        let request = URLRequest(url: url)



        let task = URLSession.shared.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                   try FileManager.default.copyItem(at: tempLocalUrl as URL, to: FileChecker().getPathURL(filename: url.lastPathComponent, directory: directory))

                    print("sucessfully downloaded the zip file ...........")
                    //unziping it
                    //self.unzipFile(url: url, directory: directory)

                } catch (let writeError) {
                        print("Error creating a file  : \(writeError)")
                }


            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }

作为初学者,我想知道 swift 中是否有任何可用的回调可以告诉我文件已下载并可用于解压缩。我正在使用 SSZipArchive 库来解压缩文件。

下面是用于解压缩它的代码

   SSZipArchive.unzipFile(atPath: path, toDestination: destinationpath)
4

1 回答 1

1

URLSession 使用两种回调机制:

  • 完成处理程序 - 这是您的代码正在使用的
  • URLSession 代表

为了具体回答您的问题,您在上面的代码中编写的完成处理程序将在下载完成时被调用。或者,如果你想在委托方法中做同样的事情,代码应该是这样的:

import Foundation
import Dispatch //you won't need this in your app

public class DownloadTask : NSObject {

    var currDownload: Int64 = -1 

    func download(urlString: String) {
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config, delegate: self,   delegateQueue: nil)

        let url = URL(string: urlString)
        let task = session.downloadTask(with: url!)
        task.resume()
    }
}


extension DownloadTask : URLSessionDownloadDelegate {

    //this delegate method is called everytime a block of data is received    
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
                       totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
        let percentage = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100
        if Int64(percentage) != currDownload  {
            print("\(Int(percentage))%")
            currDownload = Int64(percentage)
        }
    }

    //this delegate method is called when the download completes 
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //You can copy the file or unzip it using `location`
        print("\nFinished download at \(location.absoluteString)!")
    }

}

let e = DownloadTask()
e.download(urlString: "https://swift.org/LICENSE.txt")
dispatchMain() //you won't need this in your app
于 2017-12-05T08:44:40.170 回答