我已经使用此tutorial使用混合Web视图构建了Xamarin.Forms应用。我的混合Web视图使用一个本地HTML文件,其中包含呈现页面的JavaScript。
现在,我的本地HTML文件通过JavaScript接收了查询参数,并且我已经使用Hybrid View Renderer中的以下代码段在Xamarin.Android项目中成功实现了这一点:
if (e.NewElement != null)
{
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.LoadUrl($"file:///android_asset/Content/{Element.Uri}");
}
Element.Uri
包含MyFile.Html?x=1&y=2&z=3
作为字符串的地方。这样可以完美加载我的本地HTML页面。
我在Xamarin.iOS项目中无法获得同样的成功。对于我的Xamarin.iOS项目,我正在使用位于iOS Hybrid View Renderer中的以下代码段尝试加载本地HTML文件:
if (e.NewElement != null)
{
string fileName = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", Element.Uri));
NSUrl nsUrl = new NSUrl(filename, false);
Control.LoadRequest(new NSUrlRequest (nsUrl));
}
当我运行我的应用程序时,页面不呈现任何内容,也不会引发任何异常。我调试了代码,发现nsUrl.AbsoluteString
包含file:///path/to/MyFile.html%3Fx=1&y=2&z=3
,其中查询参数开头的?
已编码为%3F
。我怀疑这是问题所在。
是否可以将查询参数传递到Xamarin.iOS中的本地HTML文件?还是我采用这种方法是错误的方式?
谢谢。
答案 0 :(得分:0)
您可以将NSUrlComponents
与NSUrlQueryItem
元素数组一起使用来构建NSUrl
:
using (var contentBase = NSUrl.FromFilename(Path.Combine(NSBundle.MainBundle.BundlePath, "WebSite")))
using (var url = new NSUrlComponents
{
Scheme = "file",
Host = "localhost",
Path = Path.Combine(NSBundle.MainBundle.BundlePath, "WebSite", "index.html"),
QueryItems = new[] { new NSUrlQueryItem("x", "1"), new NSUrlQueryItem("y", "2"), new NSUrlQueryItem("z", "3") }
}.Url)
{
webView.LoadFileUrl(url, contentBase);
}
NSUrl
AbsoluteString输出:file://localhost/.../some.ios.app/WebSite/index.html?x=1&y=2&z=3