NoCached WebView

C#/Xamarin Maui 2018. 7. 22. 19:53
728x90

WebView 를 사용해 보니 cache 때문에 반영된 최신 정보를 못가져오는 경우가 있다

아래 코드를 이용하면 항상 cache 를 clear 하고 가져오므로 이런 현상을 막을수 있다.

 

PCL

namespace Project.Controls
{
    public class NoCachedWebView : WebView
    {
    }
}

 

Android

[assembly: ExportRenderer(typeof(NoCachedWebView), typeof(NoCachedWebViewRenderer))]
namespace Project.Droid.Renderer
{
    class NoCachedWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);
            if (Control == null) return;

            Control.ClearCache(true);
            Control.Settings.SetAppCacheEnabled(false);
            Control.Settings.CacheMode = Android.Webkit.CacheModes.NoCache;
        }
    }
}

 

iOS

[assembly: ExportRenderer(typeof(NoCachedWebView), typeof(NoCachedWebViewRenderer))]
namespace Project.iOS.Renderer
{
    class NoCachedWebViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
            if (Element == null) return;

            NSUrlCache.SharedCache.RemoveAllCachedResponses();
            NSUrlCache.SharedCache.MemoryCapacity = 0;
            NSUrlCache.SharedCache.DiskCapacity = 0;
        }
    }
}

728x90
Posted by kjun.kr
,