0

调用 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]参数类型。谁知道该怎么做?

4

1 回答 1

2

有一个类似的问题有一个很好的答案

您应该将allHeaderFields属性转换为您需要的类型,即[String:String],像这样:

  let foundCookies: [NSHTTPCookie]?
  if let responseHeaders = HTTPResponse.allHeaderFields as? [String:String] {
    foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:url)
  }
于 2015-11-26T06:33:35.997 回答