2015-01-13 6 views
8

검색했지만 대상 C에서만 관련 답변을 찾지 못했습니다. Swift에서 파일 다운로드 진행 상황을 확인할 수있는 방법이 있습니까? 사용자에게? 나는 iOS 프로그래밍에 익숙하지 않으며 NSURLSession을 사용해 보았지만 성공하지 못했습니다.신속한 파일 다운로드 진행 찾기

편집 : this 포스트에서 볼 수 있듯이 나는이 방법을 사용했다,하지만 난 진행 상태를 가져 오는 방법을 이해할 수없는 것 :

func downloadFile(page: NSString){ 
    finished = false 
    var statusCode:Int = 0 
    println("Download starting") 
    let url = NSURL(string: page) 

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in 

     if error != nil { 
      println("download failed with error \(error?.localizedDescription)") 
     } else { 
      println("Expected Content-Length \(response.expectedContentLength)") 
      self.contentLength = response.expectedContentLength 
      if let httpResponse = response as? NSHTTPURLResponse { 
       println("Status Code of number \(self.countDownload) is \(httpResponse.statusCode)") 
       statusCode = httpResponse.statusCode 
      } 
     } 
    } 
    task.resume() 
} 

당신을 가정 사전

+2

NSURLSession을 사용하여 어떻게 이것을 시도했으며 잘못 되었습니까? – Wain

+0

당신이 시도한 것을 우리에게 보여주세요 – ColdSteel

답변

4

에 감사를 파일을 다운로드하는 중 NSURLSessionDownloadTask이라고하는 NSURLSessionTask 하위 클래스가 있습니다. 다음은 특정 함수에 대한 NSURLSession 문서에서 발췌 한 것입니다.

대리인에게 다운로드 진행 상황을 정기적으로 알려줍니다. 예를 들어

func URLSession(_ session: NSURLSession, 
    downloadTask downloadTask: NSURLSessionDownloadTask, 
    didWriteData bytesWritten: Int64, 
    totalBytesWritten totalBytesWritten: Int64, 
    totalBytesExpectedToWrite totalBytesExpectedToWrite: Int64 
) 

, 그럴 수 출력을 수행하여 콘솔에 진행 :

는 진행 상태가

URLSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) 

에서 계산 될 수있다

println("\(totalBytesWritten)/\(totalBytesExpectedToWrite)") 
+0

저는 클로저가 아닌 위임 메서드를 사용하는 경우에만 이것이 작동한다고 생각합니다. – dar512

+0

@ dar512 사실이에요. 나는 당신이 종결자를 사용하고 있다면 진전을 알 수있는 방법이 없다고 생각한다. – Jeffrey

11

이 세 가지 중 하나입니다 프로토콜의 필수 메소드 NSURLSessionDownloadDelegate. 내 경우에는 메소드의 코드는 다음과 같습니다

  • 다운로드 기적
  • 다운로드 비동기
  • 다운로드 : 나는 세 가지 접근 방식을 구현하는 작은 프로젝트를 만든

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 
        // println("download task did write data") 
    
        let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
    
        dispatch_async(dispatch_get_main_queue()) { 
         self.progressDownloadIndicator.progress = progress 
        } 
    } 
    

    진행 중

체크 아웃 : http://goo.gl/veRkA7