Reputation: 79
Want to clear cache from Reaact-native-webView in React Native, {CookieManager.clearAll();}-Not Working in iOS
Upvotes: 6
Views: 17057
Reputation: 11
I use my own async function to clear the WebView cache. Here’s a simple approach that might help:
async function clearCache() {
setIncognito(true);
setWebKey(prevKey => prevKey + 1);
ToastAndroid.show('Cache cleared', ToastAndroid.SHORT);
await new Promise(resolve => setTimeout(resolve, 500));
setIncognito(false);
}
How it works:
First, I use useState to manage the incognito mode, initially set to false. When clearCache() is triggered, it enables incognito mode and reloads the WebView. After 500ms, it switches back to normal mode. You can adjust the timeout based on your needs. In my opinion, no casual user would perform actions that fast, so keeping the cache for a short moment can still be useful.
Upvotes: 1
Reputation: 3166
I had to clear the cache on logout, had to create a native module, and bridge it to React Native. This is the code:
// ClearWebviewCache.m
#import "ClearWebviewCache.h"
#import "WebKit/WKWebsiteDataStore.h"
@implementation ClearWebviewCache
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(clearWebviewIOS:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject){
NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
dispatch_async(dispatch_get_main_queue(), ^{
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
return resolve(@"ok");
}];
});
}
@end
Header:
#import <React/RCTBridgeModule.h>
@interface ClearWebviewCache : NSObject <RCTBridgeModule>
@end
and you can then call this in React Native:
await NativeModules.ClearWebviewCache.clearWebviewIOS();
Upvotes: 7
Reputation: 389
You can use the Incognito property in WebView for clearing the cache while you want to lunch the WebView.
<WebView
........
incognito={true}
/>
Upvotes: 18