How to save cookies in shared preferences in iOS? And How can I extract it later? I want to save the cookie from HTTPCookieStorage.shared.cookies into user defaults and then extract later Please answer in Swift 3
Try this code:
Store:
func storeCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
let serverBaseUrl = "http://example.com"
var cookieDict = [String : AnyObject]()
for cookie in cookiesStorage.cookies(for: NSURL(string: serverBaseUrl)! as URL)! {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
userDefaults.set(cookieDict, forKey: "cookiesKey")
}
Retrieve:
func restoreCookies() {
let cookiesStorage = HTTPCookieStorage.shared
let userDefaults = UserDefaults.standard
if let cookieDictionary = userDefaults.dictionary(forKey: "cookiesKey") {
for (_, cookieProperties) in cookieDictionary {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
cookiesStorage.setCookie(cookie)
}
}
}
}
My solution with Swift 4, WKWebView & iOS 11. Worked for me in a case where PHPSESSID pushed from the server was not being saved across runs of the app, with user already logged in so the sesssion should just continue. With some blurb to help debugging:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var html: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
html.navigationDelegate = self
retrieve_cookies()
}
func opensite()
{
let addr = "https://thesite.com/bla/bla"
let url = URL(string: addr)!
let request = URLRequest(url: url)
html.load(request)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
let ds = WKWebsiteDataStore.default()
let cookies = ds.httpCookieStore
cookies.getAllCookies { (cookies: [HTTPCookie]) in
for cookie in cookies {
NSLog("Known cookie at load: \(cookie.name)")
}
}
NSLog("Starting to load")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
NSLog("** Error" + error.localizedDescription)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
NSLog("Load finished")
let ds = WKWebsiteDataStore.default()
let cookies = ds.httpCookieStore
cookies.getAllCookies { (cookies: [HTTPCookie]) in
var cookieDict = [String : AnyObject]()
for cookie in cookies {
NSLog("Saved cookie: \(cookie.name)")
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
UserDefaults.standard.set(cookieDict, forKey: "cookiez")
}
}
func retrieve_cookies()
{
let ds = WKWebsiteDataStore.default()
let cookies = ds.httpCookieStore
let userDefaults = UserDefaults.standard
if let cookieDict = userDefaults.dictionary(forKey: "cookiez") {
NSLog("Retrieving cookies")
var cookies_left = 0
for (_, cookieProperties) in cookieDict {
if let _ = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
cookies_left += 1
}
}
for (_, cookieProperties) in cookieDict {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey : Any] ) {
cookies.setCookie(cookie, completionHandler: {
cookies_left -= 1
NSLog("Retrieved cookie, \(cookies_left) to go")
if cookies_left == 0 {
self.opensite()
}
})
}
}
} else {
NSLog("No saved cookies")
opensite()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With