Swift NSHTTPCookieStorage count:2

3.2k Views Asked by At
var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)

<NSHTTPCookieStorage cookies count:2>

How can I loop it each a cookie?

2

There are 2 best solutions below

0
On

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)
0
On

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")
    }
}