Monday, July 7, 2014

UIWebView issue with links only being called once.



We use UIWebView's pretty heavily in our apps.  Sometimes we use links in a page to invoke other behaviors, like pushing another UIViewController on to the navigation stack.

We noticed recently that, on an iPad, clicking such a link, popping the navigation stack, then trying to click the link again did not work.

With some investigation, it seems that the delegate method shouldStartLoadWithRequest was only being called the first time.  If another link on that same page was clicked, it would work fine; the problem only occurred when the same link was attempted two or more times consecutively.

It seems the issue is that, even if you return NO from shouldStartLoadWithRequest, UIWebView believes that the requested link is the currently viewed page - thus, clicking the link again takes no action since UIWebView thinks that it's already there.

To fix this, I found the following StackOverflow link - it describes a similar problem.  The workaround to fix the issue is to fool UIWebView into believing that it is somewhere else by using javascript to change its location.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 


    NSString *surl = [[request URL] absoluteString]; 

    NSRange r = [surl rangeOfString:@"#MYACTIONLINK"]; 
    if (r.location != NSNotFound){ 

    // do my custom action
        [[NSNotificationCenter defaultCenter] postNotificationName:NotifyHTMLViewerSelectedLink object:nil userInfo:nil]; 

        [webView stringByEvaluatingJavaScriptFromString:@"window.location='#__DUMMY_ANCHOR'"]; 
    
        return NO; 

    } 

    if ([surl hasSuffix:@"_DUMMY_ANCHOR"]) 
        return NO; 

....

No comments:

Post a Comment