How do I handle cookies and storage policies in Swift?

Handling cookies and storage policies in Swift is essential for managing user sessions and preferences effectively. This guide provides an overview of how to work with cookies and storage policies in your Swift applications.

Swift, Cookies, Storage Policies, User Sessions, User Preferences, iOS Development

This article discusses best practices for managing cookies and storage policies in Swift, including how to set, get, and delete cookies, as well as understanding storage policies in your applications.


// Example: Setting a cookie in Swift using URLSession
import Foundation

let cookieProperties: [HTTPCookiePropertyKey: Any] = [
    .domain: "example.com",
    .path: "/",
    .name: "session_id",
    .value: "123456",
    .expires: NSDate(timeIntervalSinceNow: 3600) // 1 hour
]

if let cookie = HTTPCookie(properties: cookieProperties) {
    HTTPCookieStorage.shared.setCookie(cookie)
}

// Example: Retrieving a cookie
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        print("Cookie Name: \(cookie.name), Value: \(cookie.value)")
    }
}

// Example: Deleting a cookie
if let cookie = HTTPCookieStorage.shared.cookies?.first(where: { $0.name == "session_id" }) {
    HTTPCookieStorage.shared.deleteCookie(cookie)
}
    

Swift Cookies Storage Policies User Sessions User Preferences iOS Development