关于WKWebView cookie的问题很多人都遇到过,网上资料也比较多,代码参差不齐,此代码经测试可行:
/* 处理cookie问题 */
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if #available(iOS 12.0, *) {
let cookieStore: WKHTTPCookieStore = webView.configuration.websiteDataStore.httpCookieStore
cookieStore.getAllCookies({ cookies in
self.setCookie(cookies)
})
} else {
let response = navigationResponse.response as? HTTPURLResponse
var cookies: [HTTPCookie]? = nil
if let all = response?.allHeaderFields as? [String : String], let URL = response?.url {
cookies = HTTPCookie.cookies(withResponseHeaderFields: all, for: URL)
}
self.setCookie(cookies)
}
decisionHandler(WKNavigationResponsePolicy.allow)
}
func setCookie(_ cookies: [Any]?) {
for cookie in cookies as? [HTTPCookie] ?? [] {
let httpCookie: HTTPCookie? = fixExpiresDate(with: cookie)
if let httpCookie = httpCookie {
HTTPCookieStorage.shared.setCookie(httpCookie)
}
}
}
func fixExpiresDate(with cookie: HTTPCookie?) -> HTTPCookie? {
var propertiesDic = cookie?.properties
if propertiesDic?[HTTPCookiePropertyKey.expires] == nil {
propertiesDic?[HTTPCookiePropertyKey.expires] = Date(timeIntervalSinceNow: 60 * 60 * 24 * 7)
propertiesDic?[HTTPCookiePropertyKey.discard] = 0
}
var newCookie: HTTPCookie? = nil
if let propertiesDic = propertiesDic {
newCookie = HTTPCookie(properties: propertiesDic)
}
return newCookie
}