我正在尝试让我的 Alamofire 管理器实例自动记住并设置 cookie,这是我不成功的尝试:
let cfg = NSURLSessionConfiguration.defaultSessionConfiguration()
let cooks = NSHTTPCookieStorage.sharedHTTPCookieStorage()
// makes no difference whether it's set or left at default
cfg.HTTPCookieStorage = cooks
cfg.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
let mgr = Alamofire.Manager(configuration: cfg)
mgr.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/cookies/set?stack=overflow"))).responseString {
(_, _, response, _) in
var resp = response // { "cookies": { "stack": "overflow" } }
// becomes empty if cfg.HTTPCookieStorage set to nil
}
mgr.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/cookies"))).responseString {
(_, _, response, _) in
var resp = response // { "cookies": {} }
// always empty no matter what
}
cooks.cookiesForURL(NSURL(string: "http://httpbin.org/cookies")) // 0 elements
第一个 URL 发送一个Set-Cookie : stack=overflow; Path=/
标头,然后重定向 (302) 到/cookies
(相当于第二个 URL);这在我的浏览器中运行良好(一旦我点击第一个 URL,第二个 URL 总是显示该 cookie)所以我想用 Alamofire 复制这种行为。