0
votes

I have a Xamarin Forms app that uses the WebView component to display our PWA website. We are needing the WebView component to display the cached webpages when the user does not have an internet connection. This works fine in the Xamarin: Android project with no extra code needed. However, the WKWebView that is rendered for the Xamarin: iOS project, does not appear to display any cached pages.

I am fairly new to Xamarin development, and not sure if there is a way to enable the caching for the iOS project, so that it will function offline (like the Android project does). Does anyone know how to make the WKWebView serve up the cached webpages, when there is no internet connection?

1

1 Answers

0
votes

There is a ReturnCacheDataElseLoad Cache type of NSUrlRequestCachePolicy , you can use that to load cache data first else load from web .

Have a look at apple's doc about NSURLRequestReturnCacheDataElseLoad

Use existing cache data, regardless or age or expiration date, loading from originating source only if there is no cached data.

Therefore , coding iOS Renderer as follow :

public class CustomWebViewRenderer :WkWebViewRenderer
{
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);

        if(e.NewElement != null)
        {
            NSUrlRequest request = new NSUrlRequest(new NSUrl("https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview"), NSUrlRequestCachePolicy.ReturnCacheDataElseLoad, 5);
            LoadRequest(request);
        }
    }
}