0

I'm working on making a mini browser using a UIWebView.

I'd like to provide users with a way to remove all cookies from all sites - similar to in the Chrome app where you can clear cache, etc.

What's the best way to accomplish this in a UIWebView?

Here's one idea I had:

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
   [storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
Tom Hammond
  • 5,842
  • 12
  • 52
  • 95
  • http://stackoverflow.com/questions/4471629/how-to-delete-all-cookies-of-uiwebview (isn't this just a duplicate?) – matt Mar 06 '17 at 18:14
  • Sort of, that's what I reference. But I want to let them clear everything - cache and cookies – Tom Hammond Mar 06 '17 at 18:32
  • @TomHammond Sidenote, you should not use UIWebView, as suggested by Apple multiple times, use a WKWebView instead. –  Mar 06 '17 at 18:45
  • @matt Not sure if you saw, but you can hammer as multiple duplicates now. See above where I've closed this question as both a dupe of one which shows how to clear cookies, and one which shows how to clear the cache. – JAL Mar 06 '17 at 18:47
  • Technically the latter doesn't work as it's in Swift and I wanted Objective-C, but I got the answer I needed. Thanks guys! – Tom Hammond Mar 06 '17 at 18:54
  • So why did you accept a Swift answer? – JAL Mar 06 '17 at 18:56

1 Answers1

4

Use this for clearing the cookies as well as the cache.

    URLCache.shared.removeAllCachedResponses()
    URLCache.shared.diskCapacity = 0
    URLCache.shared.memoryCapacity = 0

    webView.stringByEvaluatingJavaScript(from: "localStorage.clear();")
    let cookieJar = HTTPCookieStorage.shared
    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
    }
    UserDefaults.standard.synchronize()
Aryan Sharma
  • 625
  • 2
  • 9
  • 24