Swift中WKWebView无法设置Cookie问题求助
问题现象
- 在WKWebView中设置Cookie后,Web应用无法通过
document.cookie读取该Cookie - 将
secure属性设为false时Cookie才生效,但手动设置HttpOnly为false后,实际打印Cookie时该属性仍显示为YES
问题原因
- Cookie属性Key使用错误:直接通过
rawValue创建HttpOnly和secure对应的HTTPCookiePropertyKey不符合系统规范,iOS提供了专门的标准Key来处理这些字段 - HttpOnly属性默认值问题:如果未通过正确的Key指定
HttpOnly属性,系统会默认将其设为YES,导致JS无法读取该Cookie
修正后的代码
正确创建Cookie
let cookieProps: [HTTPCookiePropertyKey : Any] = [ HTTPCookiePropertyKey.domain: "192.168.1.2", HTTPCookiePropertyKey.path: "/", HTTPCookiePropertyKey.name: "testCookie", HTTPCookiePropertyKey.value: "test", HTTPCookiePropertyKey.expires: Date(timeIntervalSinceNow: 3600 * 24 * 30), // 使用Date类型更可靠 HTTPCookiePropertyKey.isHTTPOnly: false, // 系统标准Key,控制JS是否可读取 HTTPCookiePropertyKey.secure: false // 系统标准Key,适配http协议 ] return HTTPCookie(properties: cookieProps) ?? HTTPCookie()
Cookie设置与WebView初始化
// 务必在WKWebView初始化前完成Cookie写入 let configuration = WKWebViewConfiguration() let targetCookie = createTargetCookie() // 调用上面的Cookie创建方法 configuration.websiteDataStore.httpCookieStore.setCookie(targetCookie) { // 等待Cookie写入完成后再初始化WebView并加载页面 let webView = WKWebView(frame: .zero, configuration: configuration) if let targetUrl = URL(string: "http://192.168.1.2") { webView.load(URLRequest(url: targetUrl)) } // 将webView添加到视图层级 }
额外注意事项
- Domain匹配:确保Cookie的domain与Web页面的domain完全一致,避免跨域导致Cookie无法被识别
- Secure属性适配:如果Web页面使用
http协议,secure必须设为false,否则Cookie不会被发送到服务器,也无法被JS读取 - 执行时机:必须等待
setCookie的回调完成后再加载页面,否则Cookie可能还未写入存储,导致Web页面无法读取
内容的提问来源于stack exchange,提问作者adio
相关产品推荐
相关产品推荐

