在iOS中如何清除UIWebViews的localStorage

时间:2015-05-13 14:00:48

标签: ios swift cocoa-touch uiwebview local-storage

我现在的代码删除了*.localstorage和备份localStorage文件,但是下次打开Web视图时仍然会保留localStorage,而不管文件是否被删除。

编辑:我必须删除所有域名的localStorage! I.E.注入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)
}

3 个答案:

答案 0 :(得分:3)

我现在发现问题中的代码确实可以在手机上工作,有时候在Xcode iOS模拟器中。我很确定它与每次重建时创建新app目录的事实有关,但localStorage文件“留在后面”。我已经创建了一个新问题来回答这个问题,我将其标记为已解决,因为代码不是问题所在:iOS simulator only uses the first app folder for localStorage files but creates a new app folder for everything else

答案 1 :(得分:2)

您可以尝试在UIWebView

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

答案 2 :(得分:0)

您可以使用

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