swift4.0 Alamofire cookie 持久化

存储

//传入Alamofire的response存储Cookie
    func SaveCookie(response:DataResponse){
        // 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)
                    }
                }
            }
        }
    

你可能感兴趣的:(swift4.0 Alamofire cookie 持久化)