Web View Not Saving HTML5 Local Storage Settings

2019-09-24 17:38发布

问题:

I have a web app that works fine in Safari (it uses local storage and saves the settings and restores them).

I created a web view in Xcode 4.5.2 that loads my web app. I know by default web view doesn't support local storage so I added code to enable it but now the app doesn't work at all.

My code in AppDelegate.m:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    WebPreferences *prefs = [WebView preferences];.
    [prefs _setLocalStorageDatabasePath:@"~/Library/TestApp/LocalStorage"];


    NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSURL* fileURL = [NSURL fileURLWithPath:path];
    NSURLRequest* request = [NSURLRequest requestWithURL:fileURL];
    [self.webView.mainFrame loadRequest:request];
}

@end

This part is what I added to enable local storage:

    WebPreferences *prefs = [WebView preferences];.
    [prefs _setLocalStorageDatabasePath:@"~/Library/TestApp/LocalStorage"];

I get the following error: "Expected expression" - "No known class method for selector 'preferences'"

回答1:

-preferences is an instance method on WebView, not a class method. You'll want to do WebPreferences *prefs = [self.webView preferences] to retrieve the preferences for your WebView. In addition to calling -[WebPreferences _setLocalStorageDatabasePath:], I believe that you'll also want to call -[WebPreferences setLocalStorageEnabled:] to ensure that local storage is enabled.