Know the download progress for update an UIprogressView

懵懂的女人 提交于 2019-12-04 18:42:21

What you are doing is sending a "synchronous" request, meaning that the thread that is downloading the HTTP response will hang until all data has been fetched. It is never good to do this on a UI thread, even when you do not want display any indicator of the download's progress. I suggest using the NSURLConnection class, setting it's delegate, and responding to delegate methods. A small tutorial for this can be found at http://snippets.aktagon.com/snippets/350-How-to-make-asynchronous-HTTP-requests-with-NSURLConnection.

Once you are a connection's delegate, you can get the content length when the connection receives a response:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;   
    contentSize = [httpResponse expectedContentLength];
}

Then, to calculate the total progress of the download whenever new data arrives, do something like this:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // download data is our global NSMutableData object that contains the
    // fetched HTTP data.
    [downloadData appendData:data];
    float progress = (float)[downloadData length] / (float)contentSize;
    [progressView setValue:progress];
}

UPDATE:

Another example on how to do async HTTP with Foundation: http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/

You are using synchronous request here.

The document says - A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

Refer the class reference here

After you have read the class reference, you can either send asynchronous request or initialize the request, set delegate, and start.

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