美文网首页
swift4.0 Alamofire cookie 持久化

swift4.0 Alamofire cookie 持久化

作者: 咸鱼有只喵 | 来源:发表于2018-06-02 18:59 被阅读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)
                        }
                    }
                }
            }
        
    

    相关文章

      网友评论

          本文标题:swift4.0 Alamofire cookie 持久化

          本文链接:https://www.haomeiwen.com/subject/sxorsftx.html