我正在構建一個應用程序,一旦它連接到特定的本地網絡,它就會顯示一個活動指示符,然後開始下載圖像的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
在您的加載函數中,您可以在其中成功打印下載文件,然後在此處調用您的解壓縮函數,並在您的內容執行完成後成功解壓縮。你卡在哪裏? –