我正在开发一个使用混合原生视图控制器和UIWebView
的应用程序。应用程序登录由API处理,我有一个实用程序功能,用于将身份验证令牌保存到HTTPCookieStorage
中的cookie以及持久用户模型。
现在我想更新为WKWebView
,但它不会自动加载来自HTTPCookieStorage
的Cookie,例如UIWebView
。
我找到了一种方法来保存答案here中的响应Cookie,我可以修改答案,同时将身份验证令牌存储到我的用户模型中,但我不确定如何使用Cookie对于新的请求。我只需要将cookie添加到初始加载中,因为我将在Web视图中禁用导航。
有没有办法可以将cookie值添加到标题或其他解决方案中?
以下是我将用于从响应中获取cookie的代码。
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let urlResponse = navigationResponse.response as? HTTPURLResponse,
let url = urlResponse.url,
let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
HTTPCookieStorage.shared.setCookies(cookies , for: urlResponse.url!, mainDocumentURL: nil)
decisionHandler(.allow)
}
}
答案 0 :(得分:-1)
func webViewDidStartLoad(webView: UIWebView)
{
let currentURL: String = webView.stringByEvaluatingJavaScriptFromString("window.location.href")!
print("currentURL =\(currentURL)")
self.invalidUserNameMsg.hidden = true;
self.startActivityIndicatory()
if(!self.isLoginButtonClick)
{
let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
var cookieStr:String = ""
let cookies = cookieStorage.cookies!
let strTemp = self.linstance_url.stringByReplacingOccurrencesOfString("https://", withString: "")
for cookie in cookies {
cookieStr = cookieStr + "=" + cookie.name + "=" + cookie.value
if(cookie.name == "sid" && (cookie.value.characters.count > 100) && cookie.domain == strTemp)
{
ApplicationContext.sharedInstance.accessToken = cookie.value
ApplicationContext.sharedInstance.instanceUrl = self.linstance_url
ApplicationContext.sharedInstance.orgNamespace = orgNamespaceStr
NSUserDefaults.standardUserDefaults().setObject(cookie.value, forKey: "accessToken")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "IsSSOLogin")
NSUserDefaults.standardUserDefaults().setObject(self.linstance_url, forKey: "linstance_url")
NSUserDefaults.standardUserDefaults().synchronize()
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate;
appDelegate.isSidValue = true
NSOperationQueue.mainQueue().addOperationWithBlock {
self.ssoWebView.hidden = true
self.ssoWebViewCloseButton.hidden = true
}
if(!self.isLoginButtonClick)
{
userNameTextField.text = ""
passwordTextField.resignFirstResponder();
userNameTextField.resignFirstResponder();
loginScrollView.contentSize = CGSizeMake(loginScrollView.frame.width, loginScrollView.frame.height - 100)
self.loginButtonAction(UIButton)
self.isLoginButtonClick = true
}
}
}
}
}
func webViewDidFinishLoad(webView: UIWebView)
{
self.stopActivityIndicator()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
{
self.stopActivityIndicator()
}