Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

iphone - How to make an progress bar for an NSURLConnection when downloading a file?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];
    }
}

And then update progress like this:

- (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
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...