我正在制作一个基于WkWebView cookie来决定用户登录/注销和其他活动的应用程序。大多数情况下,它可以正常工作。有时,登录URL成功后,它无法获取cookie。并且在用户注销时无法删除cookie。甚至,当我快速登录或注销时,它显示会话的错误/先前令牌。
我的实现就像:
$.post()
代表是:
func loadWebView () {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: UIScreen.main.bounds, configuration: webConfiguration )
webView.customUserAgent = APP_IDENTITY.appending("|") + Utility.deviceID().appending("|") + PSUserDefaults.getFCMToken()
webView.navigationDelegate = self
webView.uiDelegate = self
webView.load(DOMAIN_URL)
}
extension WKWebView {
func load(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
load(request)
}
}
func cleanAllCookies() {
HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
print("All cookies deleted")
WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
records.forEach { record in
WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
print("Cookie ::: \(record) deleted")
}
}
}
func refreshCookies() {
self.configuration.processPool = WKProcessPool()
}
func removeCookies(){
let cookie = HTTPCookie.self
let cookieJar = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! {
cookieJar.deleteCookie(cookie)
print("removeCookies")
}
}
}
注销后,我将通过各种方式从扩展方法中手动删除Cookie:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// i am getting the cookies here most of the time. Sometimes , it failed to sync the cookies from here.
if #available(iOS 11.0, *) {
print(webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (webViewCookies) in
let wkHttpCookieStorage = WKWebsiteDataStore.default().httpCookieStore;
wkHttpCookieStorage.getAllCookies { (cookies) in
// Nothing comes here sometimes !
for cookie in cookies {
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("decidePolicyFor navigationAction : \(navigationAction.request.url!)")
// Each URl navigation is happen properly on time
}
// I was checking the HTTPCookieStorage with a timer when it fails to get cookies in didFinish (wkwbeview ...) delegate method.
func checkHTTPCookieStorage (){
let cookieJar = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! {
}
}
I also check the print(webView.configuration.websiteDataStore.httpCookieStore.getAllCookies({ (webViewCookies) in {} values with a timer when it fails to fetch cookies. Nothing works sometimes.
观察:大多数情况下,它会在登录时获取Cookie,并可以在注销时删除Cookie。有时我需要3到10秒才能获得Cookie,而我应用计时器来获取Cookie。有时它完全失败了。我需要重新启动应用程序,然后它才能获取Cookie。好尴尬!
我看到了一些有关wkWebview Cookies问题的博客,报告和帖子,但没有任何帮助。
我的问题:
谢谢。
答案 0 :(得分:0)
我在不同的iOS版本中发现了一些奇怪的行为。某些iOS版本将Cookie保存在
中WKWebsiteDataStore.default().httpCookieStore
和某些iOS版本将其保存在
HTTPCookieStorage.shared.cookies!
从Web URL接收/设置Cookie大约需要3到10秒。我运行一个线程来检查两个商店中的cookie。可行!