斯威夫特 - 如何知道什么时候该文件是成功地利用FileManager.default.copyItem
问题描述:
我有,我有,从网址,一次下载完成,我需要把它解压在异步方式下载的zip文件的场景从网址下载。这里的问题是FileManager.default.copyItem需要一段时间,因此我不能立即解压缩文件。下面是下载zip文件代码:斯威夫特 - 如何知道什么时候该文件是成功地利用FileManager.default.copyItem
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()
}
作为一个初学者,我想知道的是有在迅速提供任何回调,可以告诉我的文件下载,并可用于解压。我正在使用SSZipArchive库来解压缩文件。
下面是使用
SSZipArchive.unzipFile(atPath: path, toDestination: destinationpath)
答
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
您可以使用回叫像完成处理 –
函数u可以给一个示例代码或链接怎么用它呢? –