I am trying to write a couple cookies in Swift so that when I display a webview, it will be able to read those cookies and react appropriately. I found many examples of how to create the cookie and read the Apple docs but I can not seem to get a valid NSHTTPCookie object. It's always nil.
Here's my code:
let baseHost = "domain.com"
let oneYearInSeconds = NSTimeInterval(60 * 60 * 24 * 365)
func setCookie(key: String, value: AnyObject) {
var cookieProps = [
NSHTTPCookieOriginURL: baseHost,
NSHTTPCookiePath: "/",
NSHTTPCookieName: key,
NSHTTPCookieValue: value,
NSHTTPCookieSecure: "TRUE",
NSHTTPCookieExpires: NSDate(timeIntervalSinceNow: oneYearInSeconds)
]
var cookie = NSHTTPCookie(properties: cookieProps)
// This line fails due to the nil cookie
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie!)
}
My cookie
variable is nil
. I've tried many combinations of the properties including having both NSHTTPCookieOriginURL
and NSHTTPCookieDomain
, with and without NSHTTPCookieSecure
and even without NSHTTPCookieExpires
. Always nil
.
Does anyone have any ideas what I'm doing wrong?
I believe the issue is that you want to be using NSHTTTPCookieDomain
, NOT NSHTTPCookieOriginURL
.
Could you try the properties like so:
var cookieProps = [
NSHTTPCookieDomain: baseHost,
NSHTTPCookiePath: "/",
NSHTTPCookieName: key,
NSHTTPCookieValue: value,
NSHTTPCookieSecure: "TRUE",
NSHTTPCookieExpires: NSDate(timeIntervalSinceNow: oneYearInSeconds)
]
If you do not provide valid properties to the constructor, you will get a null value. You should be providing a boolean to NSHTTPCookieSecure
, not a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With