尝试在 WKWebview 中加载 url 但在 iOS 中的 SFSafariViewController 或外部 safari 中工作正常时出现会话过期错误

Getting session expired error when trying to load url in WKWebview but working fine in SFSafariViewController or external safari in iOS

我的 iOS 应用程序有一个图像缩略图列表,每次单击缩略图我们都会调用 API 以获取经过身份验证的 URL(eUnity Imageviewer URL)并且 url 有 15 分钟的会话,之后它将过期。

我的问题是,当我尝试在 WKWebView 中加载 url 时,第一次它在新安装应用程序时正确打开,但是一旦我们在 WKWebView 和我们(killed/terminate/put 在后台)应用程序,当我们回到应用程序时,它给出错误会话,每个缩略图都已过期,但相同的 url 在 SFSafariViewController 中工作正常或外部野生动物园。 WKWebView 是在存储东西吗??

我在清除 [WKWebsiteDataStore allWebsiteDataTypes]NSCachedURLResponse 和 Allow Arbitrary Loads 后检查也是 YES

您绝对需要 WKWebView 缓存吗?

坦率地说,在大多数情况下,我们在使用缓存时遇到了问题,因为必须刷新的数据无论如何都会持久化,从而导致各种错误。因此我们决定一起忽略所有缓存数据,它解决了我们遇到的缓存错误。

初始化 NSURLRequest 时,尝试将 NSURLRequestReloadIgnoringCacheData 作为 cachePolicy 参数传递。

或者,您可以尝试执行下面的代码,但请注意,它会删除应用程序内所有 NSURLRequests 的缓存响应。

[[NSURLCache sharedURLCache] removeAllCachedResponses];

NSURLCache documentation 中,您可以查看可能更适合您需要的删除缓存对象的替代方法。

祝你好运!

最后经过一番研究,我发现默认情况下 WKWebView 将 cookie 和会话存储到磁盘上,因此首先将 WKWebsiteDataStore 类型设置为 nonPersistentDataStore 因为通过设置此 属性 不会允许将数据存储在磁盘上

WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
webConfiguration.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore;
webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfiguration];

然后使用下面的代码

[webView loadRequest:request]方法之前找到并删除存储的cookie
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);
                    }];
                }
            }];
        }

上述解决方案对我有用。