2017-10-09 2 views
0

URL에서 zip 파일을 다운로드해야하고 다운로드가 완료되면 비동기식으로 압축을 풀어야합니다. 문제는 여기 FileManager.default.copyItem 언젠가 걸립니다 따라서 즉시 파일 압축을 풀 수 없습니다.Swift - FileManager.default.copyItem을 사용하여 url에서 파일을 성공적으로 다운로드하는 방법을 알고 싶습니다.

func saveZipFile(url: URL, directory: String) -> Void { 
     let request = URLRequest(url: url) 



     let task = URLSession.shared.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 as URL, to: FileChecker().getPathURL(filename: url.lastPathComponent, directory: directory)) 

        print("sucessfully downloaded the zip file ...........") 
        //unziping it 
        //self.unzipFile(url: url, directory: directory) 

       } catch (let writeError) { 
         print("Error creating a file : \(writeError)") 
       } 


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

내가 알고 싶은 초보자 인 파일이 다운로드 말해 및 압축 해제에 사용할 수있는 신속한에서 사용할 수있는 콜백이되어 아래 zip 파일을 다운로드하는 코드입니다. 파일을 압축 해제하기 위해 SSZipArchive 라이브러리를 사용하고 있습니다. 아래

SSZipArchive.unzipFile(atPath: path, toDestination: destinationpath) 
+0

당신은 u는 샘플 코드를 제공 할 수 있습니다 완료 핸들러 –

+0

같은 콜백 함수를 사용하거나 내가 사용할 수있는 방법을 연결할 수 있습니다 그거야? –

답변

0

URLSession 콜백 메커니즘 두 종류의 작동 사용하여 압축을 해제에 대한 코드입니다

  • 완료 핸들러를 -이 코드는
  • URLSession 대표
  • 을 사용하는 것입니다

귀하의 질문에 구체적으로 대답하기 위해 완료 처리기 위 코드에서 작성한 코드는 다운로드가 완료 될 때 호출됩니다. 당신이 대리자 메서드에서 동일한 작업을 수행하려는 경우 또는 코드는 다음과 같이해야한다 :

import Foundation 
import Dispatch //you won't need this in your app 

public class DownloadTask : NSObject { 

    var currDownload: Int64 = -1 

    func download(urlString: String) { 
     let config = URLSessionConfiguration.default 
     let session = URLSession(configuration: config, delegate: self, delegateQueue: nil) 

     let url = URL(string: urlString) 
     let task = session.downloadTask(with: url!) 
     task.resume() 
    } 
} 


extension DownloadTask : URLSessionDownloadDelegate { 

    //this delegate method is called everytime a block of data is received  
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, 
         totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void { 
     let percentage = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100 
     if Int64(percentage) != currDownload { 
      print("\(Int(percentage))%") 
      currDownload = Int64(percentage) 
     } 
    } 

    //this delegate method is called when the download completes 
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { 
     //You can copy the file or unzip it using `location` 
     print("\nFinished download at \(location.absoluteString)!") 
    } 

} 

let e = DownloadTask() 
e.download(urlString: "https://swift.org/LICENSE.txt") 
dispatchMain() //you won't need this in your app 
관련 문제