Clear webView cookies (Swift)

One liner in Swift 5

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

Nothing above worked for me. Using the following:

  • Swift 5
  • Xcode 12.4
  • WebKit

Below is the solution worked for me:

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")
        }
    }
}

I made it by

        let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()

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

Swift 4

func removeCookies(){
    let cookieJar = HTTPCookieStorage.shared

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