Reputation: 49
var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)
<NSHTTPCookieStorage cookies count:2>
How can I loop it each a cookie?
Upvotes: 1
Views: 3236
Reputation: 4135
With URLSession
in Swift 5 a concise way to loop through the returned 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...
}
}
}
Remember, cookies may already be inside the store. If you want a solid count, make sure - before you send the request - to clean up the Cookie store...
HTTPCookieStorage.shared.deleteCookie(cookie: HTTPCookie)
Upvotes: 0
Reputation: 3131
look at this code
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")
}
}
Upvotes: 4