UIWebView在Safari中打开链接我有一个非常简单的UIWebView,其中包含我的应用程序包中的内容。我希望Web视图中的任何链接都在Safari中打开,而不是在Web视图中打开。这可能吗?
3 回答
慕标5832272
TA贡献1966条经验 获得超4个赞
将其添加到UIWebView委托:
(编辑以检查导航类型。您还可以传递file://
相关链接的请求)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked ) { [[UIApplication sharedApplication] openURL:[request URL]]; return NO; } return YES;}
Swift版本:
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == UIWebViewNavigationType.LinkClicked { UIApplication.sharedApplication().openURL(request.URL!) return false } return true }
Swift 3版本:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == UIWebViewNavigationType.linkClicked { UIApplication.shared.openURL(request.url!) return false } return true}
Swift 4版本:
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { guard let url = request.url, navigationType == .linkClicked else { return true } UIApplication.shared.open(url, options: [:], completionHandler: nil) return false}
更新
正如openURL
iOS 10中已弃用的那样:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked ) { UIApplication *application = [UIApplication sharedApplication]; [application openURL:[request URL] options:@{} completionHandler:nil]; return NO; } return YES;}
慕容森
TA贡献1853条经验 获得超18个赞
在Swift中,您可以使用以下代码:
extension YourViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { if let url = request.url, navigationType == UIWebView.NavigationType.linkClicked { UIApplication.shared.open(url, options: [:], completionHandler: nil) return false } return true }}
确保检查URL值和navigationType。
长风秋雁
TA贡献1757条经验 获得超7个赞
接受的答案不起作用。
如果您的网页通过Javascript加载网址,navigationType
则会是UIWebViewNavigationTypeOther
。遗憾的是,其中还包括后台页面加载,例如分析。
要检测页面导航,您需要将其[request URL]
与[request mainDocumentURL]
。
此解决方案适用于所有情况:
- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type{ if ([[request URL] isEqual:[request mainDocumentURL]]) { [[UIApplication sharedApplication] openURL:[request URL]]; return NO; } else { return YES; }}
- 3 回答
- 0 关注
- 694 浏览
添加回答
举报
0/150
提交
取消