Xamarin iOS C#在UIWebView中打开Safari中的链接

我在Xamarin使用C#编写带有UIWebView的iPhone应用程序。

默认情况下,Web视图中的嵌入式链接会在同一Web视图中打开Web页面。 我希望他们喜欢在新的safari浏览器实例中启动链接页面。

在X-Code中已经回答了目标C,但据我所知,Xamarin C#

webView.LoadHtmlString(html, new NSUrl(Const.ContentDirectory, true)); 

提前致谢

亚当

如果将内容加载到UIWebView中并且您想使用Safari来打开链接,那么按照上述方式进行操作会得到一个空白页面。 您需要检查NavigationType。

 private bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navType) { if (navType == UIWebViewNavigationType.LinkClicked) { UIApplication.SharedApplication.OpenUrl(request.Url); return false; } return true; } 

您可以使用此命令在设备的浏览器(Safari)中打开网页。

 UIApplication.SharedApplication.OpenUrl(new NSUrl("www.google.com")); 

您根本不必使用UIWebView 。 如果要在UIWebView打开一些网页,在Safari打开一些网页,则需要实现ShouldStartLoad委托。 在这里,您可以确定是在UIWebView打开网页,还是在Safari打开网页。

 private bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) { // you need to implement this method depending on your criteria if (this.OpenInExternalBrowser(request)) { // open in Safari UIApplication.SharedApplication.OpenUrl(request.Url); // return false so the UIWebView won't load the web page return false; } // this.OpenInExternalBrowser(request) returned false -> let the UIWebView load the request return true; } 

最后在ViewDidLoad (或其他你初始化WebView地方)的某个地方添加以下代码。

 webView.ShouldStartLoad = HandleShouldStartLoad; 

最简单/最简单的方法是将委托分配给UIWebViewShouldStartLoad属性:

 webView.ShouldStartLoad = (w, urlRequest, navigationType) => { // Open the url in Safari here. // The urlRequest parameter is of type NSUrlRequest, you can get the URL from it. return false; //return true for urls you actually want your web view to load. }; 

确保委托对于要在Safari中加载的链接返回false,以便UIWebView不加载链接。