0

I have built a Xamarin.Forms app with a Hybrid Web View using this tutorial. My Hybrid Web View uses a local HTML file which contains JavaScript which renders the page.

Now my local HTML file takes in query parameters through JavaScript and I have successfully implemented this in my Xamarin.Android project using this snippet located in the Hybrid View Renderer:

if (e.NewElement != null)
{
    Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
    Control.LoadUrl($"file:///android_asset/Content/{Element.Uri}");
}

Where Element.Uri contains MyFile.Html?x=1&y=2&z=3 as a string. This loads my local HTML page perfectly.

I can't get the same success in my Xamarin.iOS project. For my Xamarin.iOS project, I am using this snippet, located in the iOS Hybrid View Renderer, to try and load my local HTML file:

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

When I run my app, the page renders nothing and no exceptions are thrown. I have debugged my code and noticed that nsUrl.AbsoluteString contains file:///path/to/MyFile.html%3Fx=1&y=2&z=3where the ? at the start of the query parameters have been encoded to %3F. I suspect this is the problem.

Is there a way to pass query parameters to a local HTML file in Xamarin.iOS? Or am I taking this approach the wrong way?

Thanks.

1 Answer 1

1

You can use NSUrlComponents with an array of NSUrlQueryItem elements to construct your NSUrl:

Example:

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

Resulting NSUrl AbsoluteString output:

file://localhost/.../some.ios.app/WebSite/index.html?x=1&y=2&z=3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.