Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - NSHTTPCookie is nil

Tags:

ios

swift

cookies

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?

like image 797
ShatyUT Avatar asked May 29 '15 14:05

ShatyUT


1 Answers

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.

like image 125
thatidiotguy Avatar answered Sep 25 '22 05:09

thatidiotguy