我有Webview
WKWebview
我正在加载网址。加载的网站有登录页面和主页。登录后,用户将被定向到主页。登录时,会向用户发送cookie。我想得到这个cookie,在那个时刻需要用它进行HTTP调用。因为我是iOS新手,所以我获得了一些关于获取所有cookie和特定网址的信息。但是,对于特定的网址'我没有在合适的时刻获得cookie,也不知道如何获得cookie。
所以,问题是我想知道如何观察用户已登录并且我在登录后获得了cookie。
我尝试了一些代码:
viewDidLoad中的观察者代码
NotificationCenter.default.addObserver(self, selector: #selector(cookiesConfigured(notification:)), name: .cooKieName, object: nil)
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
观察员方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("fact "+keyPath!)
if keyPath == "URL" {
let clickedUrl = webView.url?.absoluteString as String!
print("fact " + clickedUrl! )
if clickedUrl == tokenURL {
print("fact equal" )
webView.removeObserver(self, forKeyPath: "URL")
webView.addObserver(self, forKeyPath:#keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}
}else if keyPath == #keyPath(WKWebView.estimatedProgress) {
print("fact estimated progress")
if webView.estimatedProgress == 1.0 {
print("fact estimated progress 100")
NotificationCenter.default.post(name: .cooKieName, object: nil)
}
}
// guard object as? WKWebView === webView, keyPath == #keyPath(WKWebView.estimatedProgress) else { return }
// print(Float(webView.estimatedProgress))
}
通知处理程序和Cookie getter方法
@objc func cookiesConfigured(notification: Notification){
print("fact cookieconfigured")
if let cookies = HTTPCookieStorage.shared.cookies(for: URL(string: tokenURL)!) {
print("fact inLet")
for cookie in cookies {
print("fact inLet")
print("fact \(cookie)")
print("fact version \(cookie.version)")
print("fact name \(cookie.name)")
print("fact value \(cookie.value)")
print("fact expiredate \(String(describing: cookie.expiresDate))")
print("fact sessiononly \(cookie.isSessionOnly)")
print("fact domain \(cookie.domain)")
print("fact path \(cookie.path)")
print("fact issecure \(cookie.isSecure)")
}
}