小编nag*_*rrr的帖子

无法设置WKWebView设置Cookie(iOS 11+)

我拼命尝试将自定义cookie添加到WKWebView实例(不使用Javascript或类似的解决方法)。

从iOS 11及更高版本开始,Apple提供了执行此操作的API:WKWebViews WKWebsiteDataStore具有属性httpCookieStore

这是我的(示例)代码:

import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView!

    override func viewDidLoad() {
        webView = WKWebView()
        view.addSubview(webView)
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let cookie = HTTPCookie(properties: [
            HTTPCookiePropertyKey.domain : "google.com",
            HTTPCookiePropertyKey.path : "/",
            HTTPCookiePropertyKey.secure : true,
            HTTPCookiePropertyKey.name : "someCookieKey",
            HTTPCookiePropertyKey.value : "someCookieValue"])!

        let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
        cookieStore.setCookie(cookie) {
            DispatchQueue.main.async {
                self.webView.load(URLRequest(url: URL(string: "https://google.com")!))
            }
        }
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        webView.frame …
Run Code Online (Sandbox Code Playgroud)

cookies ios wkwebview wkhttpcookiestore

2
推荐指数
2
解决办法
4362
查看次数

标签 统计

cookies ×1

ios ×1

wkhttpcookiestore ×1

wkwebview ×1