var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)
<NSHTTPCookieStorage cookies count:2>
如何将每个cookie循环播放?
答案 0 :(得分:4)
看看这段代码
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")
}
}
答案 1 :(得分:0)
通过 Swift 5 中的URLSession
,可以方便地循环浏览返回的Cookie ...
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...
}
}
}
请记住,cookies可能已经在商店内部。如果您希望获得可靠的计数,请确保-在发送请求之前-清理Cookie商店...
HTTPCookieStorage.shared.deleteCookie(cookie: HTTPCookie)