iOS: How to open links externally with Safari from an app with an embedded webview?

Imagine you have an application which consists of an embedded webview that opens few local HTML pages. Perhaps, you will have one or more links which redirect the user to an external webpage, but if you do that, the webview will load the external page, and the user swill “miss” the application and this may confuse them.

What users expect is the external web page to open in a new window. HTML or Javascript is not enough to do that, but don’t panic, just add these few lines to your xcode project:
In the webview controller, inside the viewDidLoad() function:

webView.delegate = self;

Now just add these function in the controller as well:

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

That will handle the links contained from your html documents in your webview, and will force Safari to open the ones which start with “http”.

Tip: If you want to do the same with links beginning with another scheme URI like mailto, skype… just add it in the “if” condition list.

2 thoughts on “iOS: How to open links externally with Safari from an app with an embedded webview?

  1. Please help me, where do i need paste your code…

    #import “ViewController.h”

    @interface ViewController ()

    @end

    @implementation ViewController

    @synthesize webview;

    – (void)viewDidLoad

    {
    [super viewDidLoad];

    NSString *path = [[NSBundle mainBundle] pathForResource:@”introduccion” ofType:@”html” inDirectory:@”localHTML”];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webview loadRequest:request];
    }

    – (void)didReceiveMemoryWarning
    {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

    @end

Leave a Reply

Your email address will not be published. Required fields are marked *