How to manage cookies with UIWebView in Swift
Solution 1
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)
}
Solution 2
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
Solution 3
swift 2.0
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in storage.cookies! {
storage.deleteCookie(cookie)
}
NSUserDefaults.standardUserDefaults().synchronize()
Solution 4
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()
Solution 5
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)
Related videos on Youtube
ernestocattaneo
Updated on May 03, 2020Comments
-
ernestocattaneo about 4 years
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!
-
ernestocattaneo over 9 yearsHi! Te method to see cookies works great! Thank you :) A lot of people will appreciate this ;-) The one to delete cookies doesn't.. storage.deleteCookie(cookie) causes an error: "Cannot convert the expression's type AnyObject to type NSHTTPCookie -> Void
-
Dharmesh Kheni over 9 yearsI didn't check that code I just converted it into swift.now let me check this.:)
-
ernestocattaneo over 9 yearsGREAT! Just perfect! :) :) Thank you very much :)
-
Christoph about 8 yearsWhat does the last call to
NSUserDefaults.standardUserDefaults()
do? -
Alexander Volkov over 7 yearsWhat
NSUserDefaults.standardUserDefaults().synchronize()
is for? -
ingh.am about 6 yearsIt is no longer necessary according to developer.apple.com/documentation/foundation/userdefaults "func synchronize() -> Bool" "Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used." Saying that, I have seen it used in
applicationDidEnterBackground
to make sure values are synced as the app enters the background. -
xdeleon over 5 yearsJust a heads up that as of iOS 10 SDK Apple advises against calling synchronize: " this method is unnecessary and shouldn't be used" developer.apple.com/documentation/foundation/userdefaults/…
-
MartianMartian over 2 yearscan someone edit the answer to include a demo for webViewDidStartLoad ? newbie here