如何更改HTTPCookie到期日期并将其注入WKWebView

时间:2019-02-06 10:19:32

标签: ios swift oauth-2.0 wkwebview httpcookie

我有一个随OAuth2令牌响应收到的Cookie:

<NSHTTPCookie
version:0
name:JSESSIONID
value:B2680375E4F780E20CF6F3DB1D0BDC02
expiresDate:'(null)'
created:'2019-02-06 09:53:30 +0000'
sessionOnly:TRUE
domain:my.domain.name
partition:none
sameSite:none
path:/nidp
isSecure:TRUE
isHTTPOnly: YES
path:"/nidp" isSecure:TRUE isHTTPOnly: YES>

我正在尝试更改其到期日期,将sessionOnly设置为FALSE,然后将其注入WKWebView,就像此处建议的https://stackoverflow.com/a/26577303/1433612一样。

我获得了原始cookie的属性,更新了值并使用HTTPCookie初始化程序创建了一个新的properties。但是,当我打印新的Cookie实例时,即使属性已明确更新,它也会显示旧数据。我很困惑。

这是我的代码:

if let props = cookie.properties, (props[HTTPCookiePropertyKey.name] as? String) == "JSESSIONID" {
    var properties = props

    // An NSString object stating whether the cookie should be discarded at the end of the session.
    properties.updateValue("FALSE", forKey: HTTPCookiePropertyKey.discard)

    // An NSString object containing an integer value stating how long in seconds the cookie should be kept, at most.
    let sevenDays = "\(60*60*24*7)"
    properties.updateValue(sevenDays, forKey: HTTPCookiePropertyKey.maximumAge)

    let oneDay: Double = 60*60*24
    let dateAfterOneDay = Date().addingTimeInterval(oneDay)
    // An NSDate object or NSString object specifying the expiration date for the cookie.
    properties.updateValue(dateAfterOneDay, forKey: HTTPCookiePropertyKey.expires)

    let newCookie = HTTPCookie(properties: properties)!
    webView
       .configuration
       .websiteDataStore
       .httpCookieStore
       .setCookie(newCookie)
}

0 个答案:

没有答案