Wednesday, June 1, 2011

iphone webview loading percentage

Instead of using a UIWebView, you can pull the webpage down as an NSData object using an NSURLConnection. When you get the initial response from your request from

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

the webserver should return a value of "expected content size" (which should be included in the response). Then you will keep getting the following method called each time you receive data:

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

Keep appending the data to an existing NSData object. Then you can check the size of your current data object (NSData.bytes) against the expected response size.

percentage = (myData.bytes/theResponse.expectedContentSize)*100;

Then you can update a progress bar with that percentage! When

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

runs, use your data to call

[myWebView loadData:myData MIMEType:myMimeType textEncodingName:myEncoding baseURL:baseURL];

and it will load everything you pulled down into your web view.

No comments: