var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)
<NSHTTPCookieStorage cookies count:2>
我怎样才能把它循环成一个cookie?
var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)
<NSHTTPCookieStorage cookies count:2>
我怎样才能把它循环成一个cookie?
看看这段代码
var cookies:[NSHTTPCookie] = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies as [NSHTTPCookie]
for cookie:NSHTTPCookie in cookies as [NSHTTPCookie] {
if cookie.name as String == "CookieName" {
var cookieValue : String = "CookieName=" + cookie.value! as String
//if you want to add to your request
youRequest.setValue(cookieValue, forHTTPHeaderField: "cookie")
}
}
在Swift 5URLSession
中使用一种简洁的方式来遍历返回的 Cookies...
URLSession.shared.dataTask(with: url) { (data, resp, error) in
if let response = resp as? HTTPURLResponse {
print("Status Code \(response.statusCode)")
if let cookies:[HTTPCookie] = HTTPCookieStorage.shared.cookies{
for cookie:HTTPCookie in cookies as [HTTPCookie] {
// logic here...
}
}
}
请记住,cookie 可能已经在商店内。如果您想要一个可靠的计数,请确保 - 在发送请求之前 - 清理 Cookie 存储...
HTTPCookieStorage.shared.deleteCookie(cookie: HTTPCookie)