URLSession + Cookies

How can I set URLSession to accept cookies and include them in additional requests?

When you create the URLSession you can pass a URLSessionConfiguration, which has some properties you can use to change the behavior:

  • httpCookieAcceptPolicy, which determines when cookies should be accepted, defaults to onlyFromMainDocument
  • httpShouldSetCookies "determines whether requests should contain cookies from the cookie store" and defaults to true

It should accept cookies and include them on subsequent requests automatically.

Edit:
You can also grab the HTTPCookieStorage and query it for applicable cookies (via cookies(for:)). That will hand you back an optional array of HTTPCookie. You can pass the array to HTTPCookie.requestHeaderFields(with:) to get the header fields to set in requests if you want to do it manually.

To be clear, by default you don't need to configure anything, URLSession should automatically store and attach the cookies it sees.

2 Likes

Keep in mind that URLSession has different implementations on Apple and non-Apple platforms. In theory they behave identically, but that’s not always the case. So, if you’re having problems, it’s important to note which platform you’re testing on.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes