如何从 UIWebView 打开 safari.app 中的外部链接?
Posted
技术标签:
【中文标题】如何从 UIWebView 打开 safari.app 中的外部链接?【英文标题】:How can I open external links in safari.app from UIWebView? 【发布时间】:2014-06-10 10:50:43 【问题描述】:我想在 safari.app 中请求外部链接。不幸的是,它不起作用。我已经尝试了来自How can I open an external link in Safari not the app's UIWebView? 的所有代码,但它们在我的代码中都不起作用。
你有什么想法吗?我的错误在哪里?谢谢你的帮助!
这是我的代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
[self.iPhoneWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"]]];
[self.iPadWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"]]];
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
// open External Links (not beginning with http://www.example.com in Safari.app
if (
(navigationType == UIWebViewNavigationTypeLinkClicked) &&
( ![[[request URL] absoluteString] hasPrefix:@"http://www.example.com"])
)
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
//open Internal links in uiwebview
return YES;
- (void)displayActivityControllerWithDataObject:(id)obj
UIActivityViewController* vc = [[UIActivityViewController alloc]
initWithActivityItems:@[obj] applicationActivities:nil];
[self presentViewController:vc animated:YES completion:nil];
- (void)webViewDidStartLoad:(UIWebView *)webView
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
- (void)webViewDidFinishLoad:(UIWebView *)webView
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
@"<html><center><font size=+5 color='red'>Ein Fehler ist aufgetreten<br>%@</font></center></html>",
error.localizedDescription];
[self.iPhoneWebView loadHTMLString:errorString baseURL:nil];
@end
【问题讨论】:
【参考方案1】:将你的 webview 的 delegate 设置为 self,别忘了!
这对我有用:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType
if ( inType == UIWebViewNavigationTypeLinkClicked )
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
return YES;
【讨论】:
以上是关于如何从 UIWebView 打开 safari.app 中的外部链接?的主要内容,如果未能解决你的问题,请参考以下文章
如何从 UIWebView 打开 safari.app 中的外部链接?