How to manage cookies with UIWebView in Swift How to manage cookies with UIWebView in Swift ios ios

How to manage cookies with UIWebView in Swift


Try this code:

SEE COOKIES STORED

    if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies {        for cookie in cookies {            NSLog("\(cookie)")        }    }

DELETE STORED COOKIES

    var storage : NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()    for cookie in storage.cookies  as! [NSHTTPCookie]{        storage.deleteCookie(cookie)    }

swift 2.0

let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()for cookie in storage.cookies! { storage.deleteCookie(cookie)}

Swift 3.0

if let cookies = HTTPCookieStorage.shared.cookies {    for cookie in cookies {        NSLog("\(cookie)")    }}let storage = HTTPCookieStorage.sharedfor cookie in storage.cookies! {    storage.deleteCookie(cookie)}


swift 3 clear version

Save cookies

func saveCookies() {    guard let cookies = HTTPCookieStorage.shared.cookies else {        return    }    let array = cookies.flatMap { (cookie) -> [HTTPCookiePropertyKey: Any]? in        cookie.properties    }    UserDefaults.standard.set(array, forKey: "cookies")    UserDefaults.standard.synchronize()}

Load cookies :

func loadCookies() {    guard let cookies = UserDefaults.standard.value(forKey: "cookies") as? [[HTTPCookiePropertyKey: Any]] else {        return    }    cookies.forEach { (cookie) in        guard let cookie = HTTPCookie.init(properties: cookie) else {            return        }        HTTPCookieStorage.shared.setCookie(cookie)    }}

You can call these functions like the following code

func webViewDidStartLoad(_ webView: UIWebView) {    loadCookies()}func webViewDidFinishLoad(_ webView: UIWebView) {    saveCookies()}

Do not forget to have a delegate of your WebView for webViewDidStartLoad and webViewDidFinishLoad


swift 2.0

let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()for cookie in storage.cookies! { storage.deleteCookie(cookie)}NSUserDefaults.standardUserDefaults().synchronize()


matomo