2017-07-03 37 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 我發現一個提示上alamofire github上 - 到服務器響應設置 標題( 「內容長度:」 $大小); 但它不會幫助下,有誰知道?)所有其他與這個框架可以作爲應該

回答

0

對於很多人來說它的工作原理,以確保Web服務器提供了正確的Content-Length,看到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而不是Content-Length