How can I erase all cookies from the NSHTTPCookieStorage.sharedHTTPCookieStorage? The only methods I am aware of delete a single specified cookie, however, the cookies are handled behind the scenes by NSURLSession. (Programming in Swift)
Asked
Active
Viewed 5,289 times
3 Answers
16
This achieves the same result as the other answers but with one line of code:
HTTPCookieStorage.shared.cookies?.forEach(HTTPCookieStorage.shared.deleteCookie)

jwswart
- 1,226
- 14
- 16
14
let cookieStore = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in cookieStore.cookies ?? [] {
cookieStore.deleteCookie(cookie)
}

smottt
- 3,272
- 11
- 37
- 44

Andrew Johnson
- 579
- 4
- 23
-
Why this code is not generating crash for modifying collection while iterating it? Just want a confirmation on it. – Fauad Anwar May 29 '19 at 14:55
-
1@FauadAnwar Arrays in Swift are structs and thus value types, so they get copied rather than referenced. – Andrew Johnson Sep 02 '21 at 16:23
9
Similarly, for swift 3.0+, xCode 8.0+
let cookieStore = HTTPCookieStorage.shared
for cookie in cookieStore.cookies ?? [] {
cookieStore.deleteCookie(cookie)
}

Rujoota Shah
- 1,251
- 16
- 18