2015-01-13 6 views
8

私は検索しましたが、目的のCでのみ関連する回答が見つかりませんでした。Swiftでファイルのダウンロードの進捗状況を確認する方法はありますかユーザーに?私はiOSプログラミングの新人です。私はNSURLSessionを試しましたが、成功しませんでした。すぐにファイルのダウンロード進捗状況を見つける

EDIT: 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 
) 

、あなたは出力が実行して、コンソールに進行できます

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

私はこれがクロージャではなくデリゲートメソッドを使用する場合にのみ有効だと思います。 – dar512

+0

@ dar512それは本当です。私はあなたがクロージャを使用している場合、進歩を見つける方法がないと私は注意する必要があります。 – Jeffrey

11

進捗状況は、これは3の1である

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

で計算することができますプロトコルの必要なメソッドNSURLSessionDownloadDelegate。私の場合、メソッドのコードは次のようになります。

  • ダウンロード同期
  • ダウンロード非同期
  • ダウンロード:私は3つの異なるアプローチを実装して小さなプロジェクトを、作成した

    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

関連する問題