我有一个场景,我必须从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)
答案 0 :(得分:0)
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