2

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?

michalronin
  • 243
  • 2
  • 12

2 Answers2

2

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.

Andreas
  • 2,665
  • 2
  • 29
  • 38
  • 1
    That's exactly what happened. And your suggestion about `cookies(for:)` led me to a proper solution. Many thanks! – michalronin Feb 05 '17 at 16:09
2

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)")
   }
}
markhorrocks
  • 1,199
  • 19
  • 82
  • 151