草庐IT

ios - WKHTTPCookieStore getAllCookies 并不总是调用 completionHandler

coder 2023-09-07 原文

我们的应用程序允许通过 SSO 登录,我们通过启动 WKWebKit View 到与我们的服务器通信的特定 URL,并最终重定向到我们期望的 URL 来实现。在此过程中,我们获得了一个 cookie,我们需要将其传输到我们的 SessionManager,但是,当尝试从 WKHTTPCookieStore 获取 cookie 时,我们并不总是获得回调。这是一些代码:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    let httpCookieStore = WKWebsiteDataStore.default().httpCookieStore
    httpCookieStore.getAllCookies { (cookies) in
        // This block not always called!!!
    }
}

这通常发生在设备上初始安装应用程序时,并且几乎总是可以在设备上重现,但不能在模拟器中重现。

此时我已经尝试了所有我能想到的方法,但我不知道为什么回调有时会被调用而不会总是被调用。

最佳答案

要查看所有 cookie,您可以使用此代码

import UIKit

import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

var webView: WKWebView?

override func viewDidLoad() {
    super.viewDidLoad()

    let configuration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero,configuration:configuration)
    self.view = webView
}

override func viewDidAppear(_ animated: Bool) {
    let url = URL(string: "YOUR URL")

    let request = URLRequest(url: url!)

    webView?.navigationDelegate = self
    webView?.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)

    self.webView?.load(request)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    if let newValue = change?[.newKey] as? Int, let oldValue = change?[.oldKey] as? Int, newValue != oldValue {

        print("NEW",change?[.newKey])
    } else {
        print("OLD",change?[.oldKey])

    }

    webView?.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
        for cookie in cookies {
            print(cookie)
        }
    }
}
}

关于ios - WKHTTPCookieStore getAllCookies 并不总是调用 completionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54246400/

有关ios - WKHTTPCookieStore getAllCookies 并不总是调用 completionHandler的更多相关文章

随机推荐