WKHTTPCookieStore getAllCookies并不总是调用completionHandler

时间:2019-01-18 00:58:47

标签: ios swift

我们的应用程序允许通过SSO登录,这是通过将WKWebKit视图触发到与服务器通信的特定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!!!
    }
}

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

在这一点上,我已经尝试了所有可以想到的方法,但是我不知道为什么有时调用回调,但并非总是如此。

1 个答案:

答案 0 :(得分:0)

要查看所有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)
        }
    }
}
}