How to set Cookies in Alamofire such that such that every time I kill the app and restart it, the same cookie is sent?
Prepare your cookies
let cookieProps = [
HTTPCookiePropertyKey.domain: "##put your domain here##",
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.name: "##put your cookie key here##",
HTTPCookiePropertyKey.value: "##put your cookie value here##"
]
Set your cookies
if let cookie = HTTPCookie(properties: cookieProps) {
AF.session.configuration.httpCookieStorage?.setCookie(cookie)
}
After that, you can do your normal request and the cookies will be sent to server
Alamofire.request(
##URL##,
method: ##.post or .get##,
parameters: parameters
).responseString {
response in
....
}
Get cookies from response using the NSHTTPCookie
[cookiesWithResponseHeaderFields(_:forURL:)] method.
// setCookies
func setCookies(cookies: NSHTTPCookie){
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)
}
// getCookies
func getCookies() {
let parameters: [String: AnyObject] = [:]
Alamofire.request(.POST, "http://test.com/test", parameters: parameters).responseJSON { response in
if let
header = response.response?.allHeaderFields as? [String: String],
URL = response.request?.URL
{
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(header, forURL: URL)
print(cookies)
}
}
}
Swift 3:
func setCookies(cookies: HTTPCookie){
Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.setCookies(cookies, forURL: URL, mainDocumentURL: nil)
}
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters).responseData { (responseObject) -> Void in
if let resposecode = responseObject.response?.statusCode {
if resposecode != 200 {
// error
} else {
// view all cookies
print(HTTPCookieStorage.shared.cookies)
}
}
}
Swift 3.0
let cookies = HTTPCookie.cookies(withResponseHeaderFields: response.allHeaderFields , for: response.URL!)
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: URL, mainDocumentURL: nil)
Alamofire instance is shared singleton, so for all Request the cookie is set. Hope it's works for you.
Like this?
let httpCookie = HTTPCookie.init(properties:
[HTTPCookiePropertyKey.version : "0",
HTTPCookiePropertyKey.name : "MYTestID",
HTTPCookiePropertyKey.value : "983724dd3dea4924b8d675b0df08b611",
HTTPCookiePropertyKey.expires : "2027-05-13 09:21:23 +0000"])
if let cookie = httpCookie {
HTTPCookieStorage.shared.setCookie(cookie)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With