我正在尝试在Swift中编写几个cookie,以便当我显示一个webview时,它将能够读取这些cookie并做出适当的 react 。我找到了许多有关如何创建cookie和阅读Apple文档的示例,但似乎无法获得有效的NSHTTPCookie对象。总是零。

这是我的代码:

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!)
}

我的cookie变量是nil。我尝试了许多属性组合,包括同时具有NSHTTPCookieOriginURLNSHTTPCookieDomain,具有和不具有NSHTTPCookieSecure甚至没有NSHTTPCookieExpires。始终为nil

有人知道我在做什么错吗?

最佳答案

我相信问题是您想使用NSHTTTPCookieDomain,而不是NSHTTPCookieOriginURL

您可以这样尝试这些属性吗:

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

如果没有为构造函数提供有效的属性,则将获得一个空值。您应该为NSHTTPCookieSecure提供 bool 值,而不是字符串。

关于ios - Swift-NSHTTPCookie为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30532570/

10-16 12:11