How to save Cookies from HTTPURLResponse

1k Views Asked by At

I am working on a login application, After successful login response comes back with 2 cookies, i want to get this 2 cookies from the header of my HTTPURLResponse but i couldn't (httpResponse fields didn't contain the cookies) How can I find and save them for my future requests? thanks for helping me

my partial code :

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

There are 1 best solutions below

0
Efe ÖZYER On
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)
    }
}