我已经构建了一个Xamarin。使用本教程的具有混合Web视图的Forms应用程序。我的混合Web视图使用本地HTML文件,该文件包含呈现页面的JavaScript。
现在,我的本地HTML文件通过JavaScript接收查询参数,我已经在我的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混合视图渲染器中的片段来尝试加载我的本地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文件?还是我采取了错误的方法?
谢谢。
您可以将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
绝对字符串输出:
file://localhost/.../some.ios.app/WebSite/index.html?x=1&y=2&z=3