xamarin - 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 文件?还是我以错误的方式采用这种方法?
谢谢。
解决方案
您可以使用元素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
推荐阅读
- python - python中数组的乘法
- javascript - 输入类型 =“数字”的最大长度 Parlsey.js
- python - 点冻结需要 26 秒
- c# - 在 ASP.NET Core Angular 应用程序中运行时更改主题很热门
- c - ESP32变量的多重定义
- r - R生存分析:coxph - 包括时间为零的个体
- java - 您能否在用户更新到 Google Play 商店中您的应用程序的最新版本之前向他们发出警告?
- cakephp - CakePHP 3 - 即使定义了关系,也无法使用分层数据进行跨数据库 ORM 查询
- c - C - 如何迭代文本文件并检查特定字符是否存在
- python - 如何在大型数据帧上优化 while 循环