如果我关闭应用程序并随后启动应用程序,则WKWebView不会显示登录用户的内容,因为PHP $ _COOKIE ['ios_login']为空。 PHP $ _COOKIE ['ios_login']为空,因为WKWebView不发送cookie。我不知道为什么?请帮助我。
导入UIKit 导入WebKit
ViewController类:UIViewController,WKNavigationDelegate,WKUIDelegate {
var webView = WKWebView()
var timer = Timer()
var user = getUser()
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
webView.uiDelegate = self
let url = URL(string: "https://www.google.com")!
view = webView
let request = URLRequest(url: url)
webView.load(request)
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
let cookieProperty: [HTTPCookiePropertyKey: Any] = [
HTTPCookiePropertyKey.domain: "google.com",
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.name: "ios_login",
HTTPCookiePropertyKey.value: "\(user!.user_id)@\(user!.user_token)",
HTTPCookiePropertyKey.secure: "TRUE",
]
let httpCookie = HTTPCookie(properties: cookieProperty)
cookieStore.setCookie(httpCookie!, completionHandler: {() -> Void in
self.webView.reload()
})
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: (#selector(ViewController.getCookie)), userInfo: nil, repeats: true)
}
@objc func getCookie() {
self.user = getUser()
if self.user != nil {
if user!.user_id == "" {
webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
for cookie in cookies {
if cookie.name == "user_id" {
updateUserID(user: self.user!, user_id: cookie.value)
uploadUserToServer(cookie.value, user_token: self.user!.user_token)
self.webView.configuration.websiteDataStore.httpCookieStore.delete(cookie)
} else {
print("\(cookie.name) : \(cookie.value)")
}
}
}
}
}
}
}