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

…衆ロ難τιáo~ 提交于 2019-11-26 15:56:24
Stefan Arentz

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!