在我的应用程序注册中,我从服务器获取和设置 cookie 以进行用户身份验证,这是我从服务器获取的标头字段:
[Content-Type: application/json, Pragma: no-cache, X-Powered-By: PHP/5.5.29-1+deb.sury.org~precise+1, Set-Cookie: PHPSESSID_NEW=u3j95qff7100d87pimd56mfc37; 过期=格林威治标准时间 2024 年 4 月 12 日星期五 10:31:46;最大年龄=259200000;路径=/,服务器:nginx/1.1.19,内容编码:gzip,到期时间:星期四,1981 年 11 月 19 日 08:52:00 GMT,缓存控制:无存储,无缓存,必须重新验证,后check=0, pre-check=0, Date: Mon, 25 Jan 2016 10:31:46 GMT, Content-Length: 439, Connection: keep-alive, X-CDN: Incapsula, Vary: Accept-Encoding, X-信息:8-3374242-3308240 SNNY RT(1453717901817 3717) q(0 0 0 0) r(5 5) U5]
我尝试了两种使用 NSHTTPCookieStorage 设置这些字段的方法:
func setCookies(allHeaderFields:[String : String], url:NSURL){
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(allHeaderFields, forURL: url)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: url, mainDocumentURL: nil)
}
或者:
func setCookies(allHeaderFields:[String : String], url:NSURL){
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(allHeaderFields, forURL: url)
for cookie in cookies {
var cookieProperties = Dictionary<String,AnyObject>()
cookieProperties[NSHTTPCookieName] = cookie.name
cookieProperties[NSHTTPCookieValue] = cookie.value
cookieProperties[NSHTTPCookieDomain] = cookie.domain
cookieProperties[NSHTTPCookiePath] = cookie.path
cookieProperties[NSHTTPCookieVersion] = NSNumber(integer: cookie.version)
cookieProperties[NSHTTPCookieExpires] = NSDate().dateByAddingTimeInterval(31536000)
if cookie.value != "deleted"{
let newCookie = NSHTTPCookie(properties: cookieProperties)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(newCookie!)
}
}
}
我设置了另一个函数来检查和打印 cookie 是否设置正确,并在注册和登录后返回一个 NSHTTPCookie 数组,用于多种目的,它的设置很好:
func getCookies() -> [NSHTTPCookie]{
var cookiesArray:[NSHTTPCookie] = []
let cookieJar:NSHTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in cookieJar.cookies!{
print("name : \(cookie.name)")
print("value : \(cookie.value)")
print("expiresDate : \(cookie.expiresDate)")
print("sessionOnly : \(cookie.sessionOnly)")
cookiesArray.append(cookie)
}
return cookiesArray
}
在运行 iOS 9 的设备上,这两种情况下一切正常,但在运行 iOS 8 的设备上,大多数情况下应用程序被系统或用户终止(SIGKILL),持有PHPSESSID_NEW键的 cookie 是从 cookie 存储中删除,并且所有服务器调用都未经过身份验证,因此应用程序收到错误响应。我知道在以前的 iOS 版本中,当系统终止应用程序时,它也会删除 cookie,但在这种情况下,当用户终止应用程序时也会发生这种情况。任何想法为什么会发生?