Swift - 如何知道何时使用 FileManager.default.copyItem 从 url 成功下载文件 [英] Swift - How to know when the file is successfully download from url using FileManager.default.copyItem

查看:43
本文介绍了Swift - 如何知道何时使用 FileManager.default.copyItem 从 url 成功下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a scenario in which i have to download a zip file from url and once download completed i need to unzip it in async fashion. Problem here is FileManager.default.copyItem takes sometime therefore i cannot immediately unzip the file. below is code for downloading zip file :

   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 库来解压缩文件.

Being a beginner i want to know is there is any callback available in swift which can tell me the file is downloaded and is available for unzipping. I am using SSZipArchive library for unzipping the file.

下面是使用

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

推荐答案

URLSession 有两种回调机制:

URLSession works with two kinds of callback mechanisms:

  • 完成处理程序 - 这是您的代码正在使用的内容
  • URLSession 委托

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

To answer your question specifically, the completion handler that you have written in the code above will be invoked when the download is completed. Alternatively, if you want to do the same in a delegate method, the code should be something like this:

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

这篇关于Swift - 如何知道何时使用 FileManager.default.copyItem 从 url 成功下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆