首页 > 解决方案 > Xamarin.iOS:如何使用 NSUrl 将查询参数添加到 HTML 文件?

问题描述

我使用本教程构建了一个带有混合 Web 视图的 Xamarin.Forms 应用程序。我的混合 Web 视图使用包含呈现页面的 JavaScript 的本地 HTML 文件。

现在,我的本地 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 混合视图渲染器中的此代码段来尝试加载我的本地 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 文件?还是我以错误的方式采用这种方法?

谢谢。

标签: xamarinxamarin.formsxamarin.ios

解决方案


您可以使用元素NSUrlComponents数组来构造您的:NSUrlQueryItemNSUrl

例子:

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);
}

产生的NSUrlAbsoluteString 输出:

file://localhost/.../some.ios.app/WebSite/index.html?x=1&y=2&z=3

推荐阅读