如何从HTTPURLResponse

时间:2017-04-20 08:36:37

标签: swift cookies swift3 xcode8 nshttpurlresponse

我正在使用登录应用程序,成功登录后回复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()

1 个答案:

答案 0 :(得分:0)

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)
    }
}