1. 程式人生 > >iOS swift cookie創建存儲移除

iOS swift cookie創建存儲移除

storage ssa 創建 form hive ios delet view on()

保存網絡請求的cookies,並存儲到UserDefaults中

    //保存COOKIES
    static func saveCookies(for urlStr: String){
        if let url = URL(string: urlStr){
            if let cookies = HTTPCookieStorage.shared.cookies(for: url){
                var JSESSIONID = ""
                for cookie in cookies {
                        if cookie.name == "SESSION"{
                        JSESSIONID = cookie.value
                        break
                    }
                }
                if JSESSIONID.count > 0 {
                    let defaults = UserDefaults.standard
                    defaults.set(JSESSIONID, forKey: "SESSIONID")
                    defaults.synchronize()
                }
            }
        }
    }
    //如果是登錄成功一般還需要
    func saveLoginCookie(_ urlStr: String){
        let str = HOST_API + urlStr
        if let url = URL(string: str) {
           let cookies = HTTPCookieStorage.shared.cookies(for: url)
            //將cookies轉換成Data
            let data = NSKeyedArchiver.archivedData(withRootObject: cookies as Any)
            //將data存儲到userDefaults中
            UserDefaults.standard.set(data, forKey: HXQUserCookie)
        }
    }

發起網絡請求時,獲取已經保存的cookies

    static func getCookies(){
        let defaults = UserDefaults.standard
        let JSESSIONID = defaults.value(forKey: "SESSIONID") as? String
        var TOKEN = ""
        //登錄成功TOKEN
        if let cookieData = defaults.value(forKey: HXQUserCookie) as? Data{
            if cookieData.count > 0{
                if let cookies = NSKeyedUnarchiver.unarchiveObject(with: cookieData) as? Array<HTTPCookie>{
                    for cookie in cookies {
                        if cookie.name == "TOKEN"{
                            TOKEN = cookie.value
                            break
                        }
                    }
                }
            }
        }
        
        if TOKEN.count > 0 && JSESSIONID != nil {
            
            if let sessionCookie = HTTPCookie(properties: creatHTTPCookie("SESSIONID", vlaue: JSESSIONID!)) {
                HTTPCookieStorage.shared.setCookie(sessionCookie)
            }
            
            if let tokenCookie = HTTPCookie(properties: creatHTTPCookie("TOKEN", vlaue: TOKEN)) {
                HTTPCookieStorage.shared.setCookie(tokenCookie)
            }
        }
    }

    static func creatHTTPCookie(_ key: String, vlaue: String) -> [HTTPCookiePropertyKey : Any] {
        // 定義一個可變字典存放cookie鍵值對
        var properties: [HTTPCookiePropertyKey : Any] = [:]
        properties[.name] = key
        properties[.path] = "/"
        properties[.value] = vlaue
        properties[.secure] = true
        #if DEBUG
        let domain = "cs.hxquan.cn"
        #else
        let domain = "m.hxquan.cn"
        #endif
        properties[.domain] = domain
        properties[.version] = 0
        return properties
    }

這裏創建cookie的時候需要特別註意,swift中cookie創建 HTTPCookie(properties: [HTTPCookiePropertyKey : Any]),需要 [HTTPCookiePropertyKey : Any]這種格式的字典,不像oc中那麽直接的鍵值對,cookie中的name,path,value,secure,domain,version等字段都必須要有,oc中不需要。

移除保存的cookies

    static func removeCookies(){
        if let cookies = HTTPCookieStorage.shared.cookies{
            //移除cookies
            for cookie in cookies {
                HTTPCookieStorage.shared.deleteCookie(cookie)
            }
        }
        //移除userDefaults數據
        let defaults = UserDefaults.standard
        defaults.removeObject(forKey: HXQUserCookie)
        defaults.removeObject(forKey: "SESSIONID")
        defaults.synchronize()
    }

針對wkwebView的cookie的操作:
wkwebView在訪問的時候如果需要記錄用戶的操作,也需要傳入cookie,但是wkWebView不能直接通過HTTPCookieStorage來訪問cookie,需要把cookie存放在WKUserScript中

    lazy var webView: WKWebView = {[weak self] in
        let config = WKWebViewConfiguration()
        config.userContentController = WKUserContentController()
        //允許內嵌video播放
        config.allowsInlineMediaPlayback = true
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self!), name: HxqWebHandleName)
        
        let defaults = UserDefaults.standard
        var cookieDict = [String:String]()
        if let SESSIONID = defaults.value(forKey: "SESSIONID") as? String{
            cookieDict["SESSIONID"] = SESSIONID
        }
        if let cookiesData = defaults.value(forKey: HXQUserCookie) as? Data{
            if  let cookies = NSKeyedUnarchiver.unarchiveObject(with: cookiesData) as? Array<HTTPCookie> {
                for cookie in cookies{
                    if cookie.name == "TOKEN"{
                        cookieDict["SESSIONID"] = cookie.value
                        break
                    }
                }
            }
        }
        if cookieDict.keys.count == 2{
            let cookieScript = WKUserScript(source: "document.cookie = ‘TOKEN=\(cookieDict["TOKEN"]!);path=/‘;document.cookie = ‘SESSIONID=\(cookieDict["SESSIONID"]!);path=/‘", injectionTime: .atDocumentStart, forMainFrameOnly: false)
            config.userContentController.addUserScript(cookieScript)
        }
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        return webView
    }()

這裏也有一個地方需要註意的document.cookie = ‘TOKEN=(cookieDict["TOKEN"]!);path=/‘‘,這裏的path=/一定要加上,當初調試的時候因為這個問題花了很長時間才找到原因

iOS swift cookie創建存儲移除