Swift 2.0, Alamofire: Set cookies in HTTP Post Request

冷暖自知 提交于 2019-12-03 12:27:08

I had the same problem on a project and I do something like this to solve it:

let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(response.allHeaderFields as! [String: String], forURL: response.URL!)
Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)

You just have to do this one time, because the Alamofire instance is a singleton, so for all the next request the cookie is set.

Hope it's what you are looking for :)

Swift 3:

I had an array of cookies saved in my UserDefaults and what I did to attach them to the request was:

var request = URLRequest(url: "https://yourURL.com")
if let cookies = cookies as? [HTTPCookie] {
   let headers = HTTPCookie.requestHeaderFields(with: cookies)
   request.allHTTPHeaderFields = headers
}

Thanks to Jérémy, I was able to:

Alamofire.request(.POST, url, ...)
    .responseJSON { 
    response in 
    HTTPClient.updateCookies(response)
    ...
}

static func updateCookies(response: Response<AnyObject, NSError>) {
    if let
        headerFields = response.response?.allHeaderFields as? [String: String],
        URL = response.request?.URL {
        let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headerFields, forURL: URL)
        //print(cookies)
        // Set the cookies back in our shared instance. They'll be sent back with each subsequent request.
        Alamofire.Manager.sharedInstance.session.configuration.HTTPCookieStorage?.setCookies(cookies, forURL: URL, mainDocumentURL: nil)
    }
}

You could very likely make this an extension on Request, so the .storeCookies() call would be part of the .validate().responseJSON() chaining.

iOS 11 & Alamofire 4

let webDataStore = webView.configuration.websiteDataStore
webDataStore.httpCookieStore.getAllCookies { (cookies) in
    Alamofire.SessionManager.default.session.configuration.httpCookieStorage?.setCookies(
        cookies,
        for: url,
        mainDocumentURL: nil
    )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!