4

I am developing an app which uses mixed native view controllers and UIWebView. App sign in is handled by API and I have a utility function to save the auth token to a cookie in HTTPCookieStorage as well as to a persistent user model.

Now I want to update to WKWebView but it doesn't automatically load cookies from HTTPCookieStorage like UIWebView.

I found a way to save the response cookies from an answer here and I can modify the answer to also store the auth token to my user model but I'm not sure how I can use the cookies for a new request. I only need to add the cookie to the initial load as I will disable navigation in the web view.

Is there a way I can add the cookie value to the header or another solution?

Here is the code I will use to get the cookie from the response.

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)
}
}
Community
  • 1
  • 1
markhorrocks
  • 1,199
  • 19
  • 82
  • 151

1 Answers1

-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()
}