2017-07-03 4 views
0

Alamofireフレームワークを使用してサーバーからイメージをダウンロードします。私は進行状況をダウンロードする必要がありますが、私はそれを得ることはできません。Alamofire progress.fractionCompletedがnullです

Alamofire.download(requestForImage, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil, to: self.destination) 
     .downloadProgress{ progress in 
     self.progressView.progress = progress.fractionCompleted 
      print(progress.fractionCompleted) 
     } 

     .response{ response in 

      if let headers = response.response?.allHeaderFields as? [String: String]{ 
       print("headers = \(headers)") 
       // ... 
      } 


      if response.error == nil, let imagePath = response.destinationURL?.path { 
       self.progressView.progress = 1 
       let image = UIImage(contentsOfFile: imagePath) 
       print("Image is successfully downloaded!") 
       self.addNewImageToTheScrollView(img: image) 
      } 
     } 
} 

progress.fractionCompleted = 0.0、progress.totalUnitCount = -1 Iはalamofire githubの上の1つのヒントを発見 - サーバ応答を ヘッダ( "コンテンツ長:"。$サイズ)を設定します。 それは、助けて任意のアイデアを誰も持っていない?)このフレームワークと他のすべては、多くの人々のための

答えて

0

が、それはウェブサーバが正しいContent-Lengthを提供し確認するために働く必要として動作しますが、これのdidn場合https://github.com/Alamofire/Alamofire/issues/1467

を見ます頭が良くなり、Content-Lengthを読んで、あなた自身で進行状況を計算することで、小さな仕事をすることができます。

Alamofire.request(url, method: .head) 
    .validate() 
    .response { response in 

    if let error = response.error { 
     print("ERROR: Can't get head for \(url) \(error)") 
    } else { 
     if let response = response.response { 
     if let contentLengthHeader = response.allHeaderFields["Content-Length"], 
      let contentLengthInt = Int("\(contentLengthHeader)") 
     { 
      Alamofire.download(url, 
      method: .get, parameters: nil, 
      encoding: URLEncoding.default, headers: nil, to: destination 
     ) 
      .downloadProgress{ progress in 
       print(progress.fractionCompleted) 
       print(Float(progress.completedUnitCount)/Float(contentLengthInt)) 
      } 
      .validate() 
      .response{ response in 
       if let error = response.error { 
       print("ERROR: Can't get image for \(url) \(error)") 
       } else { 
       if let imagePath = response.destinationURL?.path { 
        let image = UIImage(contentsOfFile: imagePath) 
       } 
       } 
      } 
     } 
     } 
    } 
    } 

あなたがAlamofires responseJSONを使用して.json.gzなどの圧縮ファイルを、持っている場合progress.completedUnitCountはあなたに非圧縮ファイルの完成バイトを与えるので、あなたは、進捗状況を計算するために、非圧縮ファイルのサイズを知っている必要があります。

このサイズは、サーバー側のヘッダーにContent-Length-Decompressedと追加できます。上のコードでの代わりにContent-Length-Decompressedを使用するだけで十分です。

関連する問題