Alamofire Request Progress

Is it possible to show progress for

Alamofire.request(.POST, URL, parameters: parameter, encoding: .JSON) .responseJSON { response in // Do your stuff } 

I get my images / documents as a base64 string and then convert them to files in mobile

Can I show a progress bar with a percentage?

I am using Alamofire, Swift 2

+5
source share
3 answers

As you track progress in Alamofire, use closing progress on Request . More information on usage can be found in README . Although this example in README demonstrates use in a download request, it still works with data request.

An important note is that you do not always get excellent reporting from the server to request data. The reason is that the server does not always report the exact length of the content before streaming data. If the length of the content is unknown, the move will be closed, but totalExpectedBytesToRead will always be -1 .

In this situation, you can only report the exact progress if you know the approximate size of the downloaded data. You can then use the approximate number in combination with the value of totalBytesRead to calculate the estimated value of the download progress.

+8
source

To download for Swift 2.x users using Alamofire> = 3.0:

 let url = "https://httpbin.org/stream/100" // this is for example.. let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) Alamofire.download(.GET, url, parameters: params, encoding: ParameterEncoding.URL,destination:destination) .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in // This closure is NOT called on the main queue for performance // reasons. To update your ui, dispatch to the main queue. dispatch_async(dispatch_get_main_queue()) { // Here you can update your progress object print("Total bytes read on main queue: \(totalBytesRead)") print("Progress on main queue: \(Float(totalBytesRead) / Float(totalBytesExpectedToRead))") } } .response { request, _, _, error in print("\(request?.URL)") // original URL request if let error = error { let httpError: NSError = error let statusCode = httpError.code } else { //no errors let filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] print("File downloaded successfully: \(filePath)") } } 
+4
source

Alamofire 4.0 and Swift 4.x

 func startDownload(audioUrl:String) -> Void { let fileUrl = self.getSaveFileUrl(fileName: audioUrl) let destination: DownloadRequest.DownloadFileDestination = { _, _ in return (fileUrl, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(audioUrl, to:destination) .downloadProgress { (progress) in self.surahNameKana.text = (String)(progress.fractionCompleted) } .responseData { (data) in // at this stage , the downloaded data are already saved in fileUrl self.surahNameKana.text = "Completed!" } } 
+2
source

Source: https://habr.com/ru/post/1236430/


All Articles