Alex Stone
Alex Stone

Reputation: 47348

iOS UIWebView, how to block a certain URL pattern from loading?

I have an iOS app with a web view controller, which is a delegate of a web view. I would like my UIWebView to never show a url which has a certain keyword or part of a URL. (In my case, I want to block a misleading error page from the app server, which can appear in response to any request).

I'm listening to these events:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {}
-(void)webViewDidFinishLoad:(UIWebView *)webView{}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {}

I'm not sure if listening to these events is enough to make sure that all internal page redirects, including those of javascript would be inspected and the offending url will be prevented from loading.

How can I create a UIWebView which will never show a certain page?

Upvotes: 1

Views: 1021

Answers (1)

scott
scott

Reputation: 1194

You can check if the keyword is in the URL that was requested and stop the page from loading by returning false. I am assuming the keyword you are looking for will be in the URL? Let's pretend it's errorPage.

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *requestedURL = request.URL
    NSString *stringCheck = requestedURL.absoluteString;
// This is the important part--check if errorPage is in the URL.
    NSRange range = [urlString rangeOfString:@"errorPage"];
    if (range.location == NSNotFound) 
        return YES;
    else
        return NO;
}

Upvotes: 4

Related Questions