2017-03-24 94 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 
       } 

      } 
     }) 
    } 
}