Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to set cookie in NSMutableURLRequest

Tags:

swift

swift2

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?

like image 734
Mohsen Shakiba Avatar asked Jan 04 '16 12:01

Mohsen Shakiba


People also ask

How do I add cookies to my header?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.


3 Answers

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)
like image 104
Jeffery Thomas Avatar answered Oct 28 '22 04:10

Jeffery Thomas


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)")
}
like image 7
TimBigDev Avatar answered Oct 28 '22 04:10

TimBigDev


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
}
like image 4
Rishi Avatar answered Oct 28 '22 03:10

Rishi