2017-03-24 9 views
2

일단 특정 로컬 네트워크에 연결되면 활동 표시기가 표시되고 이미지의 zip 파일 다운로드가 시작됩니다. 이미지가 다운로드되면 파일을 압축 해제하고 다음 View Controller로 segue를 수행합니다. 나는 모든 기능을 작동 시키지만 기능이 끝났을 때를 감시하는 방법을 모른다. 내 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

아니요, 다운로드를 기다린 다음 다운로드의 압축을 푼 다음 연결을 수행하십시오. – Wazza

+0

로드 기능을 성공적으로 다운로드 한 곳에서 압축 해제 함수를 호출하고 성공적으로 압축을 풀어 내용을 세그먼트로 처리 한 후 압축을 해제하십시오. 어디서 붙어 있니? –

답변

1

반환 값없이 완료 핸들러를 추가하는 것은 매우 쉽습니다. 작업 호출 finished()

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

    finished() 
    } 

의 끝에서

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

load 방법을 변경하고 간단하게이 방법

load() { 
    // task has finished 
} 

load()를 호출하지만 완료 핸들러는 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 
       } 

      } 
     }) 
    } 
}