Skip to content

Commit

Permalink
Fix issue loading local files in iOS WebView (#10804)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsuarezruiz committed Nov 28, 2022
1 parent 1f2a6ae commit 73a7eb3
Showing 1 changed file with 58 additions and 6 deletions.
64 changes: 58 additions & 6 deletions src/Core/src/Platform/iOS/MauiWKWebView.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using CoreGraphics;
using Foundation;
using UIKit;
using WebKit;
using Microsoft.Extensions.Logging;

namespace Microsoft.Maui.Platform
{
Expand Down Expand Up @@ -89,13 +91,36 @@ public void LoadHtml(string? html, string? baseUrl)
}

public void LoadUrl(string? url)
{
var uri = new Uri(url ?? string.Empty);
var safeHostUri = new Uri($"{uri.Scheme}://{uri.Authority}", UriKind.Absolute);
var safeRelativeUri = new Uri($"{uri.PathAndQuery}{uri.Fragment}", UriKind.Relative);
NSUrlRequest request = new NSUrlRequest(new NSUrl(new Uri(safeHostUri, safeRelativeUri).AbsoluteUri));
{
try
{
var uri = new Uri(url ?? string.Empty);
var safeHostUri = new Uri($"{uri.Scheme}://{uri.Authority}", UriKind.Absolute);
var safeRelativeUri = new Uri($"{uri.PathAndQuery}{uri.Fragment}", UriKind.Relative);
NSUrlRequest request = new NSUrlRequest(new NSUrl(new Uri(safeHostUri, safeRelativeUri).AbsoluteUri));

LoadRequest(request);
LoadRequest(request);
}
catch (UriFormatException formatException)
{
// If we got a format exception trying to parse the URI, it might be because
// someone is passing in a local bundled file page. If we can find a better way
// to detect that scenario, we should use it; until then, we'll fall back to
// local file loading here and see if that works:
if(!string.IsNullOrEmpty(url))
{
if (!LoadFile(url))
{
if (_handler.TryGetTarget(out var handler))
handler.MauiContext?.CreateLogger<MauiWKWebView>()?.LogWarning(nameof(MauiWKWebView), $"Unable to Load Url {url}: {formatException}");
}
}
}
catch (Exception exc)
{
if (_handler.TryGetTarget(out var handler))
handler.MauiContext?.CreateLogger<MauiWKWebView>()?.LogWarning(nameof(MauiWKWebView), $"Unable to Load Url {url}: {exc}");
}
}

// https://developer.apple.com/forums/thread/99674
Expand All @@ -114,5 +139,32 @@ public static WKWebViewConfiguration CreateConfiguration()

return config;
}

bool LoadFile(string url)
{
try
{
var file = Path.GetFileNameWithoutExtension(url);
var ext = Path.GetExtension(url);

var nsUrl = NSBundle.MainBundle.GetUrlForResource(file, ext);

if (nsUrl == null)
{
return false;
}

LoadFileUrl(nsUrl, nsUrl);

return true;
}
catch (Exception ex)
{
if (_handler.TryGetTarget(out var handler))
handler.MauiContext?.CreateLogger<MauiWKWebView>()?.LogWarning(nameof(MauiWKWebView), $"Could not load {url} as local file: {ex}");
}

return false;
}
}
}

0 comments on commit 73a7eb3

Please sign in to comment.