2017-03-24 73 views
2

我正在构建一个应用程序,一旦它连接到特定的本地网络,它就会显示一个活动指示符,然后开始下载图像的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。任何帮助将非常感谢。

+0

你想从闭包中返回一些值吗? –

+0

不,只是等待下载,然后解压缩下载,然后执行segue。 – Wazza

+0

在您的加载函数中,您可以在其中成功打印下载文件,然后在此处调用您的解压缩函数,并在您的内容执行完成后成功解压缩。你卡在哪里? –

回答

1

添加不带返回值的完成处理程序非常简单。更改load方法

func load(finished: @escaping()->()) 

在任务调用finished()

let task = session.downloadTask(with: request) { ... 

    finished() 
    } 

结束,并呼吁load()只是这样

load() { 
    // task has finished 
} 

但与完成处理程序,你应该删除required init和分别拨打initload

+0

完美谢谢 – Wazza

0

您可以尝试在Downloader类中存储完成关闭。

class Downloader { 

    let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! 
    let completion: (Bool) ->() 
    required init(withCompletion completion: @escaping (Bool) ->()) { 
     self.completion = completion 
     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) 
        self.completion(true) 
       } catch (let writeError) { 
        self.completion(false) 
        print("Error creating a file \(destinationFileUrl) : \(writeError)") 
       } 

      } else { 
       self.completion(false) 
       print("Error took place while downloading a file. Error description: %@", (error?.localizedDescription)! as String); 
      } 
     } 
     task.resume() 
    } 
} 

也采取解压缩方法完成关闭。

func unZip(completion: (Bool) ->()) { 

     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) 
      completion(false) 
     } 

     let pngFiles = directoryContents.filter{ $0.pathExtension == "png" }//FIXME change file types if needed 

     imageNamesArray = pngFiles.map{ $0.deletingPathExtension().lastPathComponent } 
     completion(true) 
    } 

初始化Downloader如下。

let downloader = Downloader { (success) in 
    if success { 
    let unzip = UnZip() 
     unzip.unZip(completion: { (unzipSuccess) in 
      if unzipSuccess { 
       DispatchQueue.main.async { 
        //Stop Loading Indicator 
        //Perform Segue 
       } 

      } 
     }) 
    } 
}