gpt4 book ai didi

ios - Xamarin 表单 : WkWebView not loading website

转载 作者:行者123 更新时间:2023-11-29 05:54:13 25 4
gpt4 key购买 nike

您好,我正在使用 Xamarin(混合 WebView)的示例代码

public class Test : WKNavigationDelegate
{
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{

}
}

public class HybridWebViewRenderer : ViewRenderer<HybridWebView, WKWebView>, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
WKUserContentController userController;

protected override void OnElementChanged (ElementChangedEventArgs<HybridWebView> e)
{
base.OnElementChanged (e);

if (Control == null) {
userController = new WKUserContentController ();
var script = new WKUserScript (new NSString (JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript (script);
userController.AddScriptMessageHandler (this, "invokeAction");

var config = new WKWebViewConfiguration { UserContentController = userController };
config.WebsiteDataStore = WKWebsiteDataStore.DefaultDataStore;

var webView = new WKWebView (Frame, config);
webView.NavigationDelegate = new Test();
SetNativeControl (webView);
}
if (e.OldElement != null) {
userController.RemoveAllUserScripts ();
userController.RemoveScriptMessageHandler ("invokeAction");
var hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup ();
}
if (e.NewElement != null) {
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", "index.html"));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));


}
}

public void DidReceiveScriptMessage (WKUserContentController userContentController, WKScriptMessage message)
{
Element.InvokeAction (message.Body.ToString ());
}
}

该代码可以运行应用程序中Content文件夹中本地存储的html文件。当我更改为 new NSUrlRequest (new NSUrl("http://www.google.com ", false)));该页是空白的。

最佳答案

解决方案:

在自定义渲染器中查看这部分代码:

if (e.NewElement != null) {
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", "index.html"));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
}

这里的url结合了应用程序中的本地路径。因此,它将成功加载本地 Html,并且当您更改为 new NSUrlRequest (new NSUrl ("http://www.google.com", false))) 时将无法工作。 .

所以,如果你想加载一个网站,你应该将代码更改为:

if (e.NewElement != null) {
//string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", Element.Uri));
//Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));

//test
//Control.LoadRequest(new NSUrlRequest(new NSUrl("https://preview.pro.ant.design/user/login")));

Control.LoadRequest (new NSUrlRequest (new NSUrl (Element.Uri)));
}

关于ios - Xamarin 表单 : WkWebView not loading website,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com