iOS 中 UIWebViews 的 localStorage 有多清晰

How clear localStorage for UIWebViews in iOS

我现在的代码删除了 *.localstorage 和备份的 localStorage 文件,但是无论文件是否被删除,下次打开 web 视图时 localStorage 仍然存在。

编辑:我必须删除所有域的 localStorage! IE。注入 JS 是行不通的。

class func clearWebViewStorage() {
    let searchPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
    let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(searchPath, error:nil) as! [String]
    for file in files {
        if file.pathExtension == "localstorage" {
            NSLog("Removing localstorage file: %@", searchPath.stringByAppendingPathComponent(file))
            NSFileManager.defaultManager().removeItemAtPath(searchPath.stringByAppendingPathComponent(file), error: nil)
        }
    }

    var path = searchPath.stringByAppendingPathComponent("Backups").stringByAppendingPathComponent("localstorage.appdata.db")
    NSLog("Removing localstorage backup %@", path)
    NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
}

您可以使用

NSURLCache.sharedURLCache().removeAllCachedResponses()
NSURLCache.sharedURLCache().diskCapacity = 0
NSURLCache.sharedURLCache().memoryCapacity = 0

您还可以更改 NSURLRequest 的缓存策略

let day_url = NSURL(string: "http://www.domain.com")
let day_url_request = NSURLRequest(URL: day_url,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0)

let day_webView = UIWebView()
day_webView.loadRequest(day_url_request)

有关缓存策略的更多信息:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/index.html#//apple_ref/c/tdef/NSURLRequestCachePolicy

您可以尝试在 UIWebView

中执行此 javascript
webView.stringByEvaluatingJavaScriptFromString("localStorage.clear();")

我现在发现问题中的代码确实有效,一直在 phone 上,有时在 Xcode iOS 模拟器中。我很确定这与每次重建时创建新的应用程序目录有关,但 localStorage 文件 "stays behind"。我创建了一个新问题来回答该问题,并将其标记为已解决,因为问题不是代码:iOS simulator only uses the first app folder for localStorage files but creates a new app folder for everything else