无法设置WKWebView设置Cookie(iOS 11+) [英] WKWebView setting Cookie not possible (iOS 11+)

查看:1142
本文介绍了无法设置WKWebView设置Cookie(iOS 11+)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am desperately trying to add a custom cookie to a WKWebView instance (without using Javascript or similar workarounds).

在iOS 11及更高版本中,Apple提供了执行此操作的API:WKWebView s WKWebsiteDataStore具有属性httpCookieStore.

From iOS 11 and upwards, Apple provides an API to do this: The WKWebViews WKWebsiteDataStore has a property httpCookieStore.

这是我的(示例)代码:

Here is my (example) code:

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 = view.bounds
    }
}

此后,如果我使用webView.configuration.websiteDataStore.httpCookieStore.getAllCookies(completionHandler:),我会看到我的cookie在cookie列表中.

After this, if I use webView.configuration.websiteDataStore.httpCookieStore.getAllCookies(completionHandler:) I see that my cookie is in the list of cookies.

但是,当使用Safari的开发人员工具(当然使用iOS模拟器)检查Web视图时,cookie不会显示.

However, when inspecting the webview using Safari's developer tools (using a iOS Simulator of course) the cookie does not show up.

我还尝试使用HTTP代理(以我的情况为查尔斯)检查流量,以查看Cookie是否包含在我的HTTP请求中.不是.

I also tried to inspect the traffic using a HTTP proxy (Charles in my case) to see if the cookie in included in my HTTP requests. It is not.

我在这里做错了什么?如何将Cookie添加到WKWebView(在iOS 11及更高版本上)?

What am I doing wrong here? How can I add a cookie to WKWebView (on iOS versions 11 and up)?

推荐答案

有点晚了,但我想分享一个对我有用的解决方案,希望它也可以帮助在iOS 12上也面临相同问题的人.

A bit late but I want to share a solution that worked for me, I hope it helps someone facing the same issue on iOS 12 as well.

这是我使用的简化工作流程:

Here is the simplified workflow I used:

  1. 实例化WKWebsiteDataStore对象
  2. 将自定义Cookie设置为其httpCookieStore
  3. 等待设置cookie
  4. 实例化WKWebView
  5. 加载请求

为此,我创建了WKWebViewConfiguration的扩展:

To do that I have created an extension of WKWebViewConfiguration:

extension WKWebViewConfiguration {

static func includeCookie(cookie:HTTPCookie, preferences:WKPreferences, completion: @escaping (WKWebViewConfiguration?) -> Void) {
     let config = WKWebViewConfiguration()
     config.preferences = preferences

     let dataStore = WKWebsiteDataStore.nonPersistent()

     DispatchQueue.main.async {
        let waitGroup = DispatchGroup()

        waitGroup.enter()
        dataStore.httpCookieStore.setCookie(cookie) {
            waitGroup.leave()
        }

        waitGroup.notify(queue: DispatchQueue.main) {
            config.websiteDataStore = dataStore
            completion(config)
        }
    }
}

在我的示例中,我使用它的方式如下:

And for my example I have used it as follows:

override func viewDidLoad() {
  self.AddWebView()
}

private func addWebView(){

    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    preferences.javaScriptCanOpenWindowsAutomatically = true

    let cookie = HTTPCookie(properties: [
        .domain: COOKIE_DOMAIN,
        .path: "/",
        .name: COOKIE_NAME,
        .value: myCookieValue,
        .secure: "TRUE",
        .expires: NSDate(timeIntervalSinceNow: 3600)
        ])

     //Makes sure the cookie is set before instantiating the webview and initiating the request
     if let myCookie = cookie {
        WKWebViewConfiguration.includeCookie(cookie: myCookie, preferences: preferences, completion: {
           [weak self] config in
              if let `self` = self {
                 if let configuration = config {
                    self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.height), configuration: configuration)

                    self.view.addSubview(self.webView)
                    self.webView.load(self.customRequest)
                 }
              }
     }
}

这篇关于无法设置WKWebView设置Cookie(iOS 11+)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆