如何删除 UIWebView 的所有 cookie?

在我的应用程序中,我有一个 UIWebview,它加载用于登录的 linkedinauth 页面。当用户登录时,cookie 保存到应用程序中。

我的应用程序有一个注销按钮,这是不相关的 Linkedin 登录。所以当用户点击这个按钮时,他就会从应用程序中退出。我希望这个退出将清除他的 Linkedin Cookie 也从应用程序,这样用户将完全退出。

48949 次浏览

According to this question, you can go through each cookie in the "Cookie Jar" and delete them, like so:

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];

You could make a function inside the html of the WebView, that cleans the cookies.

If you need the cleaning to be done only once you could trigger this function with a Titanium event, only when the app starts.

Just wanted to add some info regarding this.

In OS X 10.9/iOS 7 and later, you can use -resetWithCompletionHandler: to clear the cookies and cache etc. of the whole app from your sharedSession:

Empties all cookies, caches and credential stores, removes disk files, flushes in-progress downloads to disk, and ensures that future requests occur on a new socket.

[[NSURLSession sharedSession] resetWithCompletionHandler:^{
// Do something once it's done.
}];

The for-In loop with deleteCookie: sounds like modifying while enumerating a collection to me. (Don't know, could be a bad idea?)

If anyone is looking for Swift Solution:

    let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies{
for cookie in cookies {
storage.deleteCookie(cookie)
}
}

Previous answers didn't help me in the case of using MKWebView. So, I found another solution:

func loadAuthUrl(_ url: URL) {
        

let finally: VoidClosure = { [weak self] in
guard let self = self else { return }
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
self.webView.load(request)
}
        

let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
cookieStore.getAllCookies({ [weak self] cookies in
guard let _ = self else { return }
let instagramCookies = cookies.filter({ $0.domain == ".instagram.com" })
if instagramCookies.isEmpty {
finally()
} else {
DispatchQueue.global().async(execute: {
let group = DispatchGroup()
for cookie in cookies {
group.enter()
cookieStore.delete(cookie, completionHandler: { group.leave() })
}
group.wait()
DispatchQueue.main.async(execute: finally)
})
}
})
}