How to manage cookies with UIWebView in Swift

后端 未结 8 880
心在旅途
心在旅途 2020-12-02 11:53

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 intere

8条回答
  •  爱一瞬间的悲伤
    2020-12-02 12:07

    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

提交回复
热议问题