Am tried all the methods of enable cookies, its not working, safari browser working, wkwebview not working
Method 1: let config = WKWebViewConfiguration()
let preferences = WKPreferences()
preferences.javaScriptCanOpenWindowsAutomatically = false
config.preferences = preferences
let cookieStore = WKWebsiteDataStore.nonPersistent()
config.websiteDataStore = cookieStore
webView = WKWebView(frame: view.bounds, configuration: config)
webView.navigationDelegate = self
if let url = URL(string: "https://emerald-lyssa-85.tiiny.site/") {
// Create a URLRequest with the URL
let request = URLRequest(url: url)
// Load cookies from the request
if let cookies = HTTPCookieStorage.shared.cookies(for: url) {
for cookie in cookies {
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: nil)
}
// Load the URLRequest in the webView
webView.load(request)
}
}
view.addSubview(webView)
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
guard let response = navigationResponse.response as? HTTPURLResponse,
let url = navigationResponse.response.url else {
decisionHandler(.cancel)
return
}
if let headerFields = response.allHeaderFields as? [String: String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
cookies.forEach { cookie in
webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}
}
decisionHandler(.allow)
}
These methods are am tried its not working
I am not sure if I understood your problem correctly, but..
In general,
WKWebViewhas cookies enabled by default. You can access the storeWKWebView.configuration.websiteDataStore.httpCookieStoreand play with them usinggetAllCookies(_:)andsetCookie(_:)methods, as you did.By configuring
WKWebsiteDataStore.nonPersistent()in your code snippet I assume, that you do not want to persistWKWebViewcookies between consequent app launches. On the other hand, I conclude, you want to transfer the cookies saved previously in Safari to yourWKWebViewand that is why you try to read them fromHTTPCookieStorage.shared.In HTTPCookieStorage documentation we can read that:
This means that you cannot read Safari cookies from
HTTPCookieStorage.shared.cookies(for:)because it only applies to your sandboxed app and they will not be stored there.Only
SFSafariViewControllerwould be capable of using Safari cookies, but you have no programmatic access there anyway.