Swift - How to set cookie in NSMutableURLRequest

Updated answer for Swift 3

You want to look at HTTPCookieStorage.

// First
let jar = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url)
jar.setCookies(cookies, for: url, mainDocumentURL: url)

// Then
var request = URLRequest(url: url)

Original answer for swift 2

You want to look at NSHTTPCookieStorage.

// First
let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: url)
jar.setCookies(cookies, forURL: url, mainDocumentURL: url)

// Then
let request  = NSMutableURLRequest(URL: url)

Swift 5

if let cookie = HTTPCookie(properties: [
    .domain: ".my.domain.name.com",
    .path: "/",
    .name: "myCookieNameKey",
    .value: "K324klj23KLJKH223423CookieValueDSFLJ234",
    .secure: "FALSE",
    .discard: "TRUE"
]) {
    HTTPCookieStorage.shared.setCookie(cookie)
    print("Cookie inserted: \(cookie)")
}

Tags:

Swift

Swift2