Failed to unarchive saved Httpcookie in UserDefaults

75 Views Asked by At

I'm trying to save httpcookie from WKWebview and reuse it later. I can successfully save the cookie into Userdefaults, but when I tried to read the cookie, it failed to unarchive. Here is the code.

override func viewDidLoad() {
    super.viewDidLoad()
    webView.load(URLRequest(url: URL(string: "https://ft.ual.com/")!))
    webView.navigationDelegate = self
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    
    WKWebsiteDataStore.default().httpCookieStore.getAllCookies { cookies in
        print(cookies)
        setData(cookies, key: "cookies")
        if let savedCookies: [HTTPCookie] = getData(key: "cookies") {
            print("saved cookies:")
            print(savedCookies)
            // I tried to read cookies here, but it prints "failed to get data"
        }
    }

    decisionHandler(.allow)

}

Helper functions:

func setData(_ value: Any, key: String) {
    let ud = UserDefaults.standard
    do {
        let archivedPool = try NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false)
        ud.set(archivedPool, forKey: key)

    } catch {
        print("failed to archive data")
    }
}

func getData<T>(key: String) -> T? {
    let ud = UserDefaults.standard
    if let val = ud.value(forKey: key) as? Data {
        do {
            if let obj = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSData.self, from: val) as? T {
                return obj
            }
            return nil
        } catch {
            print("failed to get data")
        }
    }
    return nil
}

0

There are 0 best solutions below