How to open link in Safari from an HTML hosted in a web browser control?
We have an iphone app that hosts a web browser control which points to a website whose sole purpose is to display information for the application. I would like开发者_StackOverflow社区 to know if it is possible to have an anchor/button open Safari using HTML/JavaScript. If it is possible, how so?
Thanks...
You can setup a delegate for the UIWebview you are using. In this delegate, write something like this:
-(bool) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//You might need to set up an "interceptLinks"-Bool since you don't want to intercept the initial loading of the content
if (self.interceptLinks) {
NSURL *url = request.URL;
//This launches Safari with your URL
[[UIApplication sharedApplication] openURL:url];
return NO;
}
//No need to intercept the initial request to fill the WebView
else {
self.interceptLinks = TRUE;
return YES;
}
}
If you only want to intercept some links, you can parse the url and only open Safari if necessary.
Set the delegate property of your UIWebView object (what you call the 'web browser control') to an object of your own that implements the method "webView:shouldStartLoadWithRequest:navigationType:" of the UIWebViewDelegate protocol:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html%23//apple_ref/occ/intf/UIWebViewDelegate
You can then detect if you desired URL is being requested and in that case open it on an external Safari instance using UIApplication's openURL method.
You can use something like this:
myWebView.ShouldStartLoad += LoadHook;
[...]
bool LoadHook (UIWebView sender, NSUrlRequest request, UIWebViewNavigationType navType){
var requestString = request.Url.AbsoluteString;
// determine here if this is a url you want to open in Safari or not
if (WantToOpenInSafari (requestString)){
UIApplication.SharedApplication.OpenUrl (new NSUrl (requestString));
return true;
} else {
return false;
}
}
精彩评论