iOS Development

ios – Didn’t unarchive saved Httpcookie in UserDefaults – Stack Overflow

I am attempting to avoid wasting httpcookie from WKWebview and reuse it later. I can efficiently save the cookie into Userdefaults, however once I tried to learn the cookie, it didn’t unarchive. Right here is the code.

override func viewDidLoad() {
    tremendous.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 attempted to learn cookies right here, however it prints "didn't get information"
        }
    }

    decisionHandler(.permit)

}

Helper features:

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

    } catch {
        print("didn't archive information")
    }
}

func getData<T>(key: String) -> T? {
    let ud = UserDefaults.customary
    if let val = ud.worth(forKey: key) as? Information {
        do {
            if let obj = attempt NSKeyedUnarchiver.unarchivedObject(ofClass: NSData.self, from: val) as? T {
                return obj
            }
            return nil
        } catch {
            print("didn't get information")
        }
    }
    return nil
}

Credit: www.ismmailgsm.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button