Skip to content

Instantly share code, notes, and snippets.

@RickyAvina
Last active June 17, 2017 05:10
Show Gist options
  • Save RickyAvina/3a3dafb40e9257a667b499600bf1f78e to your computer and use it in GitHub Desktop.
Save RickyAvina/3a3dafb40e9257a667b499600bf1f78e to your computer and use it in GitHub Desktop.
Swift Cookie Collector
func getCookies(response: HTTPURLResponse)-> [HTTPCookie] {
var cookies = [HTTPCookie()]
let field = response.allHeaderFields as? [String: String]
if let url = response.url {
cookies = HTTPCookie.cookies(withResponseHeaderFields: field!, for: url)
HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: nil)
for cookie in cookies {
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] = NSDate().addingTimeInterval(31536000)
let newCookie = HTTPCookie(properties: cookieProperties)
HTTPCookieStorage.shared.setCookie(newCookie!)
}
}
return cookies
}
@RickyAvina
Copy link
Author

Function for simply collecting cookies from an HTTPRequest. Usage:

var request = URLRequest(url: NSURL(string: "https://example.com") as! URL)
request.httpMethod = "GET"

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

let task = session.dataTask(with: request) { (data, response, error) in
    if let httpResponse = response as? HTTPURLResponse{
        let cookies = self.getCookies(response: httpResponse)
        print(cookies)
    }
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment