我有一个班级:
class Test: UIViewController, NSURLSessionDelegate {
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
let responseHeaderFields = (response ).allHeaderFields as! [String : String]
var nR = NSMutableURLRequest(URL: request.URL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: NSTimeInterval(30))
nR.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaderFields, forURL: response.URL!))
for header in responseHeaderFields {
nR.setValue(
header.1,
forHTTPHeaderField: header.0
)
}
completionHandler(nR)
}
func myMethod() {
//some code...
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
session.dataTaskWithRequest(urlRequest, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) in
guard let responseData = data else {
return
}
guard error == nil else {
return
}
//....
}
}
}
当我致电myMethod
时,我发布了将商品添加到购物车的请求。此帖子请求创建cookie购物车并将我重定向到另一个URL。但我尝试捕获重定向,然后将cookie和另一个标头数据设置到下一个网址是不行的:(任何想法为什么?
答案 0 :(得分:1)
不确定这是否是您所追求的,但如果您只想将Cookie从请求移至另一个请求,则可以使用NSHTTPCookieStorage。
保存原始回复的Cookie,并在需要时使用相同的网址检索它们。
走吧:
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:originalResponse.URL];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:originalResponse.URL mainDocumentURL:nil];
如果您需要阅读cookie,请致电:
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:originalResponse.URL];