Thank you!
Here is my code in Xcode. It works.
Do you have any further better solutions for my code?
// Create the WKWebView instance. Add a cookie store observer.
if #available(iOS 11, *){
let wkWebView = WKWebView()
wkWebView.configuration.websiteDataStore.httpCookieStore.add(OnShiftWKHTTPCookieStoreObserver())
}
// this is how we're adding cookies to our WKWebView instance.
let ExpTime = TimeInterval(60 * 60 * 24 * 365 * 50)
let cookies: [HTTPCookiePropertyKey : Any] = [
HTTPCookiePropertyKey.domain: ".mydomain.de", // fill up width my domain
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.name: "testcookie",
HTTPCookiePropertyKey.value: "test",
HTTPCookiePropertyKey.secure: "TRUE",
HTTPCookiePropertyKey.expires: NSDate(timeIntervalSinceNow: ExpTime),
HTTPCookiePropertyKey.version: "0"
]
if #available(iOS 11, *) {
let wkWebView = WKWebView()
let cookiesStore = wkWebView.configuration.websiteDataStore.httpCookieStore
if let cookie = HTTPCookie(properties: cookies) {
cookiesStore.setCookie(cookie, completionHandler: {
print ("cookie added: \(cookie.name)")
})
// print("GET COOKIE \(HTTPCookieStorage.shared.cookies)")
}
else {
print("set cookie failed")
}
}
// This is our WKHTTPCookieStoreObserver implementation. Note that "cookiesDidChange" isn't called
// even after several calls to setCookie above.
class OnShiftWKHTTPCookieStoreObserver: NSObject, WKHTTPCookieStoreObserver {
@available(iOS 11.0, *)
func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
cookieStore.getAllCookies({(cookies: [HTTPCookie]) in
cookies.forEach({(cookie: HTTPCookie) in
print("COOKIE name: \(cookie.name) domain: \(cookie.domain) value: \(cookie.value)")
})
})
}
}