swift4.0 Alamofire cookie 持久化

2018-06-02  本文已影响178人  咸鱼有只喵

存储

//传入Alamofire的response存储Cookie
    func SaveCookie(response:DataResponse<Any>){
        // SAVE COOKIE||||||||||||||||||
        
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.request?.url
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        var cookieArray = [ [HTTPCookiePropertyKey : Any ] ]()
        for cookie in cookies {
            cookieArray.append(cookie.properties!)
        }
        UserDefaults.standard.set(cookieArray, forKey: "tokens")


    }
    

读取

      if let cookieArray = UserDefaults.standard.array(forKey: "tokens") {
            for cookieData in cookieArray {
                if let dict = cookieData as? [HTTPCookiePropertyKey : Any] {
                    if let cookie = HTTPCookie.init(properties : dict) {
                        HTTPCookieStorage.shared.setCookie(cookie)
                    }
                }
            }
        }
    
上一篇下一篇

猜你喜欢

热点阅读