Search code examples
htmliosuiwebviewuipopover

How to make UIWebView Links open in a UIPopover?


I currently have a simple HTML file loaded in a UIWebView with a bunch of links embedded in the text of the file. I am wondering if there is a way to make these links open in a UIPopover.

The links are to another HTML file, so I would like them to load in a UIPopover with a UIWebView inside them.

Let me know if I haven't been clear enough as to what I'm looking for.


Solution

  • You should look at this method of UIWebViewDelegate

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

    This will get called whenever a user triggers a link

    So make the viewController which contains the UIWebView into that webView's delegate, and implement this method.

    If has a BOOL return value. If you return "NO" the webview itself will not attempt to handle the link, so you can take control of it.

    (NSURLRequest *)request gives you the actual link...

    So from here you can trigger a UIPopover with a content viewController... which can contain a UIWebView, in which you can load your link data.

    (funny you should ask the question just this moment, I am implementing something similar right now..)

    update

    As you noticed, there is a subtlety to observe here. When your UIWebView first loads it's content (on viewDidLoad for example), this delegate method will be called. If you return NO under this condition, the initial content will not load, and you will have a mysteriously blank webView.

    To fix this you need to consider the navigationType parameter. Basically you only want to return 'NO' if the navigationType is UIWebViewNavigationTypeLinkClicked (you activate a link). Otherwise you want to return YES (the webView should load it's content).

    So a full implementation of the method might look like this

    -               (BOOL)webView:(UIWebView *)webView
       shouldStartLoadWithRequest:(NSURLRequest *)request
                   navigationType:(UIWebViewNavigationType)navigationType
    {
      BOOL result = YES;
        if (navigationType=UIWebViewNavigationTypeLinkClicked){
            [self launchPopOverWithRequest:request]
            result =  NO;
       }
       return result;
    }