如何在下载文件时为NSURLConnection创建进度条? [英] How to make an progress bar for an NSURLConnection when downloading a file?
问题描述
我想在使用NSURLConnection进行下载时显示进度条。当我从服务器获取数据时,我可以更新每个收到的包的UI。但问题是:我如何计算出已经有多少数据,以及需要下载多少数据?可能以字节为单位......然后我必须做一些数学计算以获得百分比?
I want to show up an progress bar while a download with NSURLConnection is happening. As I am getting data from the server, I could update the UI for every received package. But the problem is: How do I figure out how much data I have already, and how much data has to be downloaded? Probably in bytes... And then I have to do some math to get the percentage?
推荐答案
在你的<$ c $中c> NSURLConnection 委托,实现类似的内容以查找总内容长度。服务器必须支持这一点,但它很可能与静态内容一起使用:
In your NSURLConnection
delegate, implement something like this to find out the total content length. The server has to support this, but it will most likely work fine with static content:
- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
{
statusCode_ = [response statusCode];
if (statusCode_ == 200) {
download_.size = [response expectedContentLength];
}
}
然后像这样更新进度:
- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
[data_ appendData: data];
download_.progress = ((float) [data_ length] / (float) download_.size);
// Broadcast a notification with the progress change, or call a delegate
}
在我的情况下,我有一个下载实例,其中包含 size
和 progress
属性。它们由全局 DownloadManager
对象拥有,该对象将负责通知感兴趣的各方下载进度或状态更改。
In my case I have a download instance that has size
and progress
properties. They are owned by a global DownloadManager
object that will take care of notifying interested parties of the download progress or state changes.
这篇关于如何在下载文件时为NSURLConnection创建进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!