Swift 3: how to check if cookies for particular URL are configured?

1.9k views Asked by At

I'm building an app for an API with cookie-based validation, and am having several issues with it.

My current problem is a function to check if autologin cookie is configured for the domain, but I can't get my head around setting it up properly.

My current attempt is:

func cookiesConfigured() -> Bool {
    let cookieStorage = HTTPCookieStorage.shared.dictionaryWithValues(forKeys: ["AutologinCookie"])
    if !cookieStorage.isEmpty {
        return true
    } else {
        return false
    }
    return false // <- will never be executed
}

What would be the right way to check the cookie storage's contents for a particular cookie?

2

There are 2 answers

1
Andreas On BEST ANSWER

As you might have realized, dictionaryWithValues is an NSObject-method and doesn't do what you think it does.

What you need is to chain cookiesFor, filter and isEmpty.

0
markhorrocks On

Here is Swift 3 code to get a particular cookie.

let cookieJar = HTTPCookieStorage.shared

for cookie in cookieJar.cookies! {

   if cookie.name == "MYNAME" {

      let cookieValue = cookie.value

      print("COOKIE VALUE = \(cookieValue)")
   }
}