Monday, June 3, 2013

UIWebView UIWebViewNavigationTypeLinkClicked example in Objective C (iOS).


UIWebView UIWebViewNavigationTypeLinkClicked

UIWebViewNavigationType
Constant indicating the user’s action.

enum {
UIWebViewNavigationTypeLinkClicked,
UIWebViewNavigationTypeFormSubmitted,
UIWebViewNavigationTypeBackForward,
UIWebViewNavigationTypeReload,
UIWebViewNavigationTypeFormResubmitted,
UIWebViewNavigationTypeOther
};
typedef NSUInteger UIWebViewNavigationType;

Constants
UIWebViewNavigationTypeLinkClicked
User tapped a link.
UIWebViewNavigationTypeFormSubmitted
User submitted a form.
UIWebViewNavigationTypeBackForward
User tapped the back or forward button.
UIWebViewNavigationTypeReload
User tapped the reload button.
UIWebViewNavigationTypeFormResubmitted
User resubmitted a form.
UIWebViewNavigationTypeOther
Some other action occurred.

UIWebView UIWebViewNavigationTypeLinkClicked example.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSURL *requestURL =[ [ request URL ] retain ];
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [ [ requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ] isEqualToString: @"mailto" ])
        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
        return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
    }
    [ requestURL release ];
    return YES;
}

Example of [UIWebView UIWebViewNavigationTypeLinkClicked].
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return false;
    }
    return true;
}

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

    // Check if this was a click event and then some other criteria for determining if you want to launch Safari.
    if (navigationType == UIWebViewNavigationTypeLinkClicked && [Some other criteria]) {
        [[UIApplication sharedApplication] openURL:request.URL];

        // Return false to indicate to the UIWebView to not navigate to the linked target
        return false;
    }

    // Return true so that the UIWebView loads the link target
    return true;
}

End of UIWebView UIWebViewNavigationTypeLinkClicked example article.