17

I'm trying to set cookie in my HTTP request and I thought that below code would work:

let request  = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("key=value;", forHTTPHeaderField: "Cookie")

but this code is not working. does anyone have idea how to set it?

Parth Pandya
  • 1,460
  • 3
  • 18
  • 34
Mohsen Shakiba
  • 1,762
  • 3
  • 22
  • 41

4 Answers4

27

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)
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • after quite app and reopen cookies gone. – Bunthoeun Jan 04 '21 at 09:48
  • @Bunthoeun using `"key=value"` creates a session cookie. If you want a cookie that lasts longer than the session, you need to set max age. `"key=value;path=/;max-age=30758400"` sets a cookie that lasts 1 year. See [Set-Cookie Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) for more information. – Jeffery Thomas Jan 04 '21 at 19:17
8

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)")
}
TimBigDev
  • 511
  • 8
  • 7
5

This may be useful for some one(Swift 5). Avoid using NSMutableURLRequest in Swift. Instead follow the below snippet:

func request(with url: URL) -> URLRequest {
    var request = URLRequest(url: url)

    guard let cookies = HTTPCookieStorage.shared.cookies(for: url) else {
        return request
    }

    request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies)
    return request
}
Rishi
  • 743
  • 8
  • 17
2

Here is how it works in Swift 3.x after you set cookie using HTTPCookieStorage

let cookies=HTTPCookieStorage.shared.cookies(for: URL(string: cookieURL)!)
let headers=HTTPCookie.requestHeaderFields(with: cookies!)
let request  = NSMutableURLRequest(url: requestURL!)
request.allHTTPHeaderFields=headers
Rujoota Shah
  • 1,251
  • 16
  • 18