Junior — Middle
Have you had experience working with client-side data storage mechanisms through cookies?
sobes.tech AI
Answer from AI
Yes, in iOS, the HTTPCookieStorage class is used to work with cookies, which allows you to save, retrieve, and delete cookies related to web requests.
For example, when working with WKWebView or URLSession, you can manage cookies as follows:
// Getting all cookies
let cookieStorage = HTTPCookieStorage.shared
if let cookies = cookieStorage.cookies {
for cookie in cookies {
print("Cookie name: \(cookie.name), value: \(cookie.value)")
}
}
// Adding a cookie
let cookieProperties: [HTTPCookiePropertyKey: Any] = [
.domain: "example.com",
.path: "/",
.name: "userToken",
.value: "abc123",
.secure: "TRUE",
.expires: Date().addingTimeInterval(3600)
]
if let cookie = HTTPCookie(properties: cookieProperties) {
cookieStorage.setCookie(cookie)
}
Thus, cookies allow you to save user state or other information on the client side.