Swift - NSHTTPCookie - Zero

I am trying to write a couple of cookies in Swift so that when it displays a webview, it can read these cookies and respond accordingly. I found many examples of how to create a cookie and read Apple docs, but I cannot get a valid NSHTTPCookie object. It is always zero.

Here is 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 have tried many combinations of properties, including both NSHTTPCookieOriginURL and NSHTTPCookieDomain , with and without NSHTTPCookieSecure and even without NSHTTPCookieExpires . Always nil .

Does anyone have any ideas what I'm doing wrong?

+7
ios cookies swift
source share
1 answer

I believe the problem is that you want to use NSHTTTPCookieDomain , NOT NSHTTPCookieOriginURL .

Could you try the following properties:

 var cookieProps = [ NSHTTPCookieDomain: baseHost, NSHTTPCookiePath: "/", NSHTTPCookieName: key, NSHTTPCookieValue: value, NSHTTPCookieSecure: "TRUE", NSHTTPCookieExpires: NSDate(timeIntervalSinceNow: oneYearInSeconds) ] 

If you do not provide valid properties for the constructor, you will get a null value. You must provide the boolean value NSHTTPCookieSecure , not a string.

+9
source

All Articles