My iOS app has a list of image thumbnails, on every click of thumbnail we are calling API to get the authenticated URL(eUnity Imageviewer URL) and url have 15 minutes session after that it will expire.
My question is when I am trying to load the url in WKWebView
, first time it is opening properly when application is newly installed but once we opened that URL on WKWebView
and we (killed/terminate/put in background) the app and when we come back to application it is giving error session expired for every thumbnail but same url is working fine in SFSafariViewControlle
r or external safari. is WKWebView
storing something??
I checked after clearing the [WKWebsiteDataStore allWebsiteDataTypes]
, NSCachedURLResponse
and Allow Arbitrary Loads is also YES
.
Finally after some research i found that by default WKWebView was storing cookies and session onto the disk so first set the WKWebsiteDataStore
type as nonPersistentDataStore
because by setting this property will not allow to store the data on disk
WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
webConfiguration.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore;
webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfiguration];
Then find and delete the stored cookies before the [webView loadRequest:request]
method with below code
if (@available(iOS 9.0, *)) {
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
NSError *errors;
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
} else {
WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
[dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
for (WKWebsiteDataRecord *record in records) {
NSLog(@"All records - %@ and data type - %@", record, record.dataTypes);
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{
NSLog(@"Cookies for %@ deleted successfully",record.displayName);
}];
}
}];
}
This above solution worked for me.