ernestocattaneo
ernestocattaneo

Reputation: 1207

How to manage cookies with UIWebView in Swift

What about have a topic where people can easily see how to manage cookies in a webview using the new language Swift? If you check in internet you won't find anything interesting when you need to implement this. Even the documentation by apple is poor.

Do anybody know how to handle these process in Swift? This is what I found but in Obj-C:

SEE COOKIES STORED

NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [cookieJar cookies]) {
NSLog(@"%@", cookie);
}

DELETE STORED COOKIES

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

It would be nice for everybody if we can give for one time an answer to this! Cheers!

Upvotes: 23

Views: 29138

Answers (8)

pansora abhay
pansora abhay

Reputation: 912

If you are working on swift 4 then this code will disable cookies and also remove the URL cache.

let cookieJar : HTTPCookieStorage = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! as [HTTPCookie]{
    NSLog("cookie.domain = %@", cookie.domain)
     cookieJar.deleteCookie(cookie)
}

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

Upvotes: 2

BYCHKOVSKIY
BYCHKOVSKIY

Reputation: 29

Logout for api VKontakte, swift 3+

let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
    for record in records {
        if record.displayName.contains("facebook") {
            dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
                print("Deleted: " + record.displayName);
            })
        }
    }
}

Upvotes: 0

VelocityPulse
VelocityPulse

Reputation: 632

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

Upvotes: 8

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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.shared
for cookie in storage.cookies! {
    storage.deleteCookie(cookie)
}

Upvotes: 46

mathema
mathema

Reputation: 988

Here is the complete answer with how to capture cookies with UIWebView's delegate function:

func webViewDidFinishLoad(_ webView: UIWebView) {
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            print("cookie= \(cookie)")
        }
    }
}

Keep in mind that cookies will saved as default and this delegate function calls every movement that finished with webview load. (It's also updated with Swift 3.0.1)

Upvotes: 2

ifedapo olarewaju
ifedapo olarewaju

Reputation: 3441

swift 3

    let storage = HTTPCookieStorage.shared

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

Upvotes: 0

magnuskahr
magnuskahr

Reputation: 1320

swift 2.0

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

Upvotes: 5

zzpaf
zzpaf

Reputation: 93

Thanks for the swift "translation"... Just needed to change the deletion to as! to force downcast:

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

Upvotes: 3

Related Questions