如何在alamofire中设置Cookies?

问题描述 投票:4回答:4

如何在Alamofire中设置Cookies,以便每当我杀死应用程序并重新启动它时,都会发送相同的cookie?

ios iphone swift alamofire
4个回答
4
投票

使用NSHTTPCookie [cookiesWithResponseHeaderFields(_:forURL :)]方法从响应中获取cookie。

// 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)
        }
    }
}

斯威夫特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)
                    }
                }
           }

3
投票

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实例是共​​享单例,因此对于所有请求,cookie都已设置。希望它对你有用。


1
投票

像这样?

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)
    }

0
投票
if let fields = response.response?.allHeaderFields as? [String : String]{
            let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: (response.request?.url!)!)
            HTTPCookieStorage.shared.setCookies(cookies, for: (response.request?.url!)!, mainDocumentURL: nil)
        }
© www.soinside.com 2019 - 2024. All rights reserved.