0

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()
aminoo
  • 59
  • 4
  • i tried it but didn't work for me , im using Swift 3 and Rob is using swift 2, unfortunately is not the same – aminoo Apr 20 '17 at 08:45

1 Answers1

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)
    }
}
Efe ÖZYER
  • 381
  • 1
  • 5
  • 10