我试图在WKWebView中设置特定URL的cookie。大多数情况下,它返回cookie,但有时返回nil。
extension WKWebView {
private var httpCookieStore: WKHTTPCookieStore {
return WKWebsiteDataStore.default().httpCookieStore
}
func getCookies(for domain: String? = nil, completion: @escaping ([String : Any])->()) {
var cookieDict = [String : AnyObject]()
HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always
httpCookieStore.getAllCookies { (cookies) in
for cookie in cookies {
HTTPCookieStorage.shared.setCookie(cookie)
ATBClientHandler.shared.isCookieFound = true
if let domain = domain {
if cookie.domain.contains(domain) {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
} else {
cookieDict[cookie.name] = cookie.properties as AnyObject?
}
}
print("myCookie: \(cookieDict)")
completion(cookieDict)
}
}}
实施
self.webView.getCookies(for: self.webView.url?.host) { (data) in
print(data)
}
在上面的代码“ myCookie:”中有时返回正确的值。但是有时“ myCookie:”返回[:],有时cookie数组本身为nil。请任何人帮助我解决这个问题。谢谢