Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone SDK: UIWebView to stop images from loading/downloading

How can I use the UIWebView in Xcode so that when it loads up pages it DOESN'T download the images (to cause a faster loading page)?

like image 930
Domness Avatar asked Feb 25 '09 17:02

Domness


2 Answers

UIWebView is a pale, poor little shadow of WebKit's full WebView, for which this is easy. -webView:shouldStartLoadWithRequest:navigationType: only gets called for navigation. It doesn't get called for every request like WebPolicyDelegate does on mac. With UIWebView, here's how I would attack this problem:

Implement -webView:shouldStartLoadWithRequest:navigationType: and set it to always return NO. But you'll also take the request and spawn an NSURLConnection. When the NSURLConnection finishes fetching the data, you're going to look through it for any IMG tags and modify them to whatever placeholder you want. Then you will load the resulting string into the UIWebView using -loadHTMLString:baseURL:.

Of course parsing the HTML is not a trivial task on iPhone, and Javascript loaders are going to give you trouble, so this isn't a perfect answer, but it's the best I know of.

like image 96
Rob Napier Avatar answered Nov 15 '22 08:11

Rob Napier


expanding on Rob's answer. I noticed that when loadHTMLString:baseURL: and always returning NO, that webView:shouldStartLoadWithRequest:navigationType: just keeps getting called. (i suspect loadHTMLString invokes another shouldStartLoadWithRequest).

so what I had to do was alternate between returning YES/NO and I used NSScanner to parse the HTML and change src="http://..." to src=""

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (pageHasNoImages==YES)
    {
        pageHasNoImages=FALSE;
        return YES;     
    }
    NSString* newHtml;
    NSString* oldHtml;
    NSData *urlData;
    NSURLResponse *response;
    NSError *error;
    urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    oldHtml=[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

    newHtml=[self.detail scannerReplaceImg:oldHtml]; // my own function to parse HTML
    newHtml=[self.detail scannerReplaceAds:newHtml]; // my own function to parse HTML
    if (newHtml==nil) 
    {
        NSLog(@"newHtml is nil");
        newHtml=oldHtml;
    }
    [oldHtml release];

    pageHasNoImages=TRUE;
    [web loadHTMLString:newHtml baseURL:request.URL];

    return NO;
}
like image 41
roocell Avatar answered Nov 15 '22 08:11

roocell