1
var httpCookie:NSHTTPCookieStorage=NSHTTPCookieStorage.sharedHTTPCookieStorage();
println(httpCookie)

<NSHTTPCookieStorage cookies count:2>

我怎样才能把它循环成一个cookie?

4

2 回答 2

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")
    }
}
于 2015-01-29T10:09:24.017 回答
0

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)
于 2020-06-12T09:04:04.737 回答