在经历了很多痛苦和挫折之后,我找到了一种启用本地存储并让它在应用程序正常运行时保持不变的方法。此解决方案专门针对 OSX,但也可能适用于 iOS。
下载此头文件并将其添加到您的项目中。它不包含在 XCode Webkit 发行版中。
click to download WebStorageManagerPrivate.h
添加以下几行:
static NSString* _storageDirectoryPath();
+ (NSString *)_storageDirectoryPath;
这些允许您检索 WebKit 本地存储跟踪器数据库的目录位置。这很重要,因为由于 WebKit 中的一个错误,如果您不将 LocalStorage WebView 文件存储在与跟踪器数据库相同的目录中,那么每隔一次运行应用程序时它们就会被删除。我没有在 WebStorageManager 代码中看到为单个应用程序更改此位置的方法。它始终从用户首选项中读取。
在您的 appDelegate 中包含 WebStorageManagerPrivate.h。
#include "WebStorageManagerPrivate.h"
您需要下载 XCode 发行版中未包含的另一个标头并将其包含在您的项目中。将其保存为 WebPreferencesPrivate.h
click to download WebPreferencesPrivate.h
在您的 appDelegate 中包含 WebPreferencesPrivate.h。
#include "WebPreferencesPrivate.h"
现在在您的 applicationDidFinishLaunching 处理程序中使用以下代码来初始化和启用 LocalStorage。该代码假定您有一个名为“webView”的 IBOutlet,用于您正在使用的 WebView。
NSString* dbPath = [WebStorageManager _storageDirectoryPath];
WebPreferences* prefs = [self.webView preferences];
NSString* localDBPath = [prefs _localStorageDatabasePath];
// PATHS MUST MATCH!!!! otherwise localstorage file is erased when starting program
if( [localDBPath isEqualToString:dbPath] == NO) {
[prefs setAutosaves:YES]; //SET PREFS AUTOSAVE FIRST otherwise settings aren't saved.
// Define application cache quota
static const unsigned long long defaultTotalQuota = 10 * 1024 * 1024; // 10MB
static const unsigned long long defaultOriginQuota = 5 * 1024 * 1024; // 5MB
[prefs setApplicationCacheTotalQuota:defaultTotalQuota];
[prefs setApplicationCacheDefaultOriginQuota:defaultOriginQuota];
[prefs setWebGLEnabled:YES];
[prefs setOfflineWebApplicationCacheEnabled:YES];
[prefs setDatabasesEnabled:YES];
[prefs setDeveloperExtrasEnabled:[[NSUserDefaults standardUserDefaults] boolForKey: @"developer"]];
#ifdef DEBUG
[prefs setDeveloperExtrasEnabled:YES];
#endif
[prefs _setLocalStorageDatabasePath:dbPath];
[prefs setLocalStorageEnabled:YES];
[self.webView setPreferences:prefs];
}
我希望这可以帮助其他人一直在努力或仍在努力解决这个问题,直到它在 WebKit 中得到正确修复。