清除webView cookie(Swift)

时间:2015-08-27 17:56:55

标签: swift cookies webview oauth

如何清除webView中少数主机的所有Cookie? this问题的方法无效。

我正在尝试使用vk.com oauth并且它没有用户注销方法,因此删除cookis是使其他用户可以登录的现有方法之一

答案在

之下

7 个答案:

答案 0 :(得分:9)

我是通过

制作的
let cookie = NSHTTPCookie.self
        let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()

        for cookie in cookieJar.cookies! {
           // print(cookie.name+"="+cookie.value)
            cookieJar.deleteCookie(cookie)
        }

Swift 4

func removeCookies(){
    let cookie = HTTPCookie.self
    let cookieJar = HTTPCookieStorage.shared

    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
    }
}

答案 1 :(得分:5)

swift 4

func removeCookies(){
    let cookie = HTTPCookie.self
    let cookieJar = HTTPCookieStorage.shared

    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
    }
}

答案 2 :(得分:2)

UIWebView几乎已弃用。 因此,对于WKWebView实例,请编写以下代码:

let cookieStore = webView.configuration.websiteDataStore.httpCookieStore

cookieStore.getAllCookies {
    cookies in

    for cookie in cookies {
        cookieStore.delete(cookie)
    }
}

答案 3 :(得分:2)

以上没有对我有用。 使用以下内容:

  • 斯威夫特 5
  • Xcode 12.4
  • WebKit

以下是对我有用的解决方案:

func removeCookies() {
    HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
    print("All cookies deleted")

    WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
        records.forEach { record in
            WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
            print("Cookie ::: \(record) deleted")
        }
    }
}

答案 4 :(得分:1)

Swift 5中的一个内衬

HTTPCookieStorage.shared.cookies?.forEach(HTTPCookieStorage.shared.deleteCookie)

答案 5 :(得分:0)

通过避免强制展开

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

如果您只想删除特定的cookie

let DOMAIN_NAME = "abc.com"
private func clearCookie(){
    let storage = HTTPCookieStorage.shared
    if let cookies = storage.cookies{
        for cookie in cookies {
            if(cookie.domain.contains(DOMAIN_NAME)){
                storage.deleteCookie(cookie)
            }
        }
    }
}

答案 6 :(得分:0)

要根据日期删除的变化。 .distantPast 删除所有

HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)