在调用API时,我会收到此消息:
<NSHTTPURLResponse: 0x7f96f0510f80> { URL: https://insula.magister.net/api/sessie } { status code: 201, headers {
"Cache-Control" = "max-age=120, private";
"Content-Length" = 0;
Date = "Thu, 30 Jul 2015 17:27:11 GMT";
"Set-Cookie" = "SESSION_ID=c8714acb-22f8-4295-90ee-82e9469890e1; domain=insula.magister.net; path=/api; secure; httponly";
"Strict-Transport-Security" = "max-age=31536000";
Vary = "Accept-Encoding,Cookie";
"X-Frame-Options" = DENY;
} }
print(HTTPResponse.allHeaderFiles)
打印以下输出:
[Set-Cookie: SESSION_ID=65a59001-de75-41ff-ad22-70549baa96f5; domain=insula.magister.net; path=/api; secure; httponly, Strict-Transport-Security: max-age=31536000, Date: Thu, 30 Jul 2015 17:33:13 GMT, X-Frame-Options: DENY, Content-Length: 0, Cache-Control: max-age=120, private, Vary: Accept-Encoding,Cookie]
但是我无法让cookiesWithResponseHeaderFields
工作,我应该传递一个[String:String]
数组作为第一个参数,但响应似乎并不相符。
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(HTTPResponse.allHeaderFields, forURL: url)
但由于HTTPResponse.allHeaderFiles
是[NSObject:AnyObject]
类型的数组,因此无法满足[String:String]
参数类型。
谁知道该怎么办?
答案 0 :(得分:1)
similar question great answer。
您应该将allHeaderFields
属性转换为您需要的类型,即[String:String]
,如下所示:
let foundCookies: [NSHTTPCookie]?
if let responseHeaders = HTTPResponse.allHeaderFields as? [String:String] {
foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:url)
}