簡體   English   中英

如何從HTTPURLResponse保存Cookies

[英]How to save Cookies from HTTPURLResponse

我正在開發一個登錄應用程序,成功的登錄響應返回2個cookie后,我想從我的HTTPURLResponse的標頭中獲得這2個cookie,但我卻無法(httpResponse字段不包含這些cookie),我如何找到並保存它們以備將來使用? 謝謝你幫我

我的部分代碼:

let task = URLSession.shared.dataTask(with: request ) { data, response, error in


        if let httpResponse = response as? HTTPURLResponse, let fields = httpResponse.allHeaderFields as? [String : String] {

            let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: (response?.url!)!)

            for cookie in cookies {
                //print ("hi")
                var cookieProperties = [HTTPCookiePropertyKey: Any]()
                cookieProperties[HTTPCookiePropertyKey.name]    = cookie.name
                cookieProperties[HTTPCookiePropertyKey.value]   = cookie.value
                cookieProperties[HTTPCookiePropertyKey.domain]  = cookie.domain
                cookieProperties[HTTPCookiePropertyKey.path]    = cookie.path
                cookieProperties[HTTPCookiePropertyKey.version] = NSNumber(value: cookie.version)
                cookieProperties[HTTPCookiePropertyKey.expires] = cookie.expiresDate

                let newCookie = HTTPCookie(properties: cookieProperties)
                HTTPCookieStorage.shared.setCookie(newCookie!)
            }            }
    }
    task.resume()
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0

if let cookies = HTTPCookieStorage.shared.cookies { 
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM