我正在构建一个应用程序,一旦它连接到特定的本地网络,它就会显示一个活动指示符,然后开始下载图像的zip文件,一旦图像下载完成,解压缩文件,停止指示器,然后执行segue到下一个View控制器。我有所有的功能工作,但不知道如何监视功能何时结束。我Donloader类看起来是这样的:downloadTask完成后执行segue
class Downloader {
let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
required init() {
self.load()
}
func load() {
// Create destination URL
let destinationFileUrl = documentsUrl.appendingPathComponent("Images.zip")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://127.0.0.1:4567/download")//FIXME for production
//Create Session
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.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, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", (error?.localizedDescription)! as String);
}
}
task.resume()
}
}
和我的我的文件类中解压缩功能如下:
func unZip() {
let zipFileURL = documentsURL?.appendingPathComponent("Images.zip")
SSZipArchive.unzipFile(atPath: (zipFileURL?.path)!, toDestination: (documentsURL?.path)!)
var directoryContents = [URL]()
do {
// Get the directory contents urls (including subfolders urls)
directoryContents = try fileManager.contentsOfDirectory(at: documentsURL!, includingPropertiesForKeys: nil, options: [])
} catch let error as NSError {
print(error.localizedDescription)
}
let pngFiles = directoryContents.filter{ $0.pathExtension == "png" }//FIXME change file types if needed
imageNamesArray = pngFiles.map{ $0.deletingPathExtension().lastPathComponent }
}
我看了一下关门,而是不知道如何给他们打电话来自课外或其他ViewController。任何帮助将非常感谢。
你想从闭包中返回一些值吗? –
不,只是等待下载,然后解压缩下载,然后执行segue。 – Wazza
在您的加载函数中,您可以在其中成功打印下载文件,然后在此处调用您的解压缩函数,并在您的内容执行完成后成功解压缩。你卡在哪里? –