Swift 2.0, Alamofire: Set cookies in HTTP Post Request

前端 未结 4 565
长情又很酷
长情又很酷 2021-02-14 00:48

I want to set cookies in my HTTP POST request.

Something like the cookie field in the HTTP Request below,

version: 0.1.7
Cookie: client=Android; version=         


        
4条回答
  •  心在旅途
    2021-02-14 01:39

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

    Alamofire.request(.POST, url, ...)
        .responseJSON { 
        response in 
        HTTPClient.updateCookies(response)
        ...
    }
    
    static func updateCookies(response: Response) {
        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.

提交回复
热议问题