【问题标题】:Xamarin.iOS: How to add query parameters to HTML file with NSUrl?Xamarin.iOS:如何使用 NSUrl 将查询参数添加到 HTML 文件?
【发布时间】:2019-02-13 10:49:42
【问题描述】:

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

现在我的本地 HTML 文件通过 JavaScript 接收查询参数,并且我已经使用位于混合视图渲染器中的这个 sn-p 在我的 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 中的这个 sn-p 来尝试加载我的本地 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 文件?还是我采用这种方法是错误的?

谢谢。

【问题讨论】:

    标签: xamarin xamarin.forms xamarin.ios


    【解决方案1】:

    您可以使用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);
    }
    

    产生NSUrlAbsoluteString 输出:

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

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2019-05-30
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多