swift2 Alamofire请求的进展情况

yruzcnhs  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(209)

是否有可能显示

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

我得到我的图像/文档作为一个base64字符串,然后我把它转换为文件在移动的
我可以用百分比显示进度条吗?
我使用的是Alamofire、Swift 2

0tdrvxhp

0tdrvxhp1#

在Alamofire中监控进度的方法是在Request上使用progress闭包。更多关于用法的详细信息可以在README中找到。虽然README中的示例演示了下载请求的用法,但它仍然适用于数据请求。
需要注意的一点是,对于数据请求,服务器并不总是能提供完美的报告。原因是服务器在流式传输数据之前并不总是报告准确的内容长度。如果内容长度未知,则会调用progress闭包,但totalExpectedBytesToRead将始终为-1
在这种情况下,只有在知道下载数据的大致大小时,才能报告准确的进度。然后,可以将大致数字与totalBytesRead值结合使用,以计算估计的下载进度值。

bogh5gae

bogh5gae2#

Alamofire 4.0和雨燕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!"
    }
}
xzabzqsa

xzabzqsa3#

要为Alamofire〉= 3.0的Swift 2.x用户下载进度:

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)")
                    }
            }

相关问题