0
votes

Hi I replaced UIWebview with WKWebview. Because on multiple frame loading UIWebview keyborad is dismissing. So i used WKWebView. my issue was gone now.

But on WKWebView im not getting cookies. it is returning only JSESSIONID cookie, Where as on UIWebView im getting all the cookies.

Please help me on this.

Here is my code snippet for start WKWebView.

   func startWebView() {
        URLCache.shared.removeAllCachedResponses()
        if webView == nil {

            let source =
                "var meta = document.createElement('meta'); " +
                    "meta.name = 'viewport'; " +
                    "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'; " +
                    "var head = document.getElementsByTagName('head')[0]; " +
            "head.appendChild(meta);"

            let script = WKUserScript(source:source,
                                      injectionTime: .atDocumentEnd,
                                      forMainFrameOnly: true)

            let userContentController = WKUserContentController()
            userContentController.addUserScript(script)

            let configuration = WKWebViewConfiguration()
            configuration.userContentController = userContentController
            let prefs = WKPreferences()
            prefs.javaScriptEnabled = true
            configuration.preferences = prefs
            webView = WKWebView(frame: CGRect.zero, configuration: configuration)

            webView.navigationDelegate = self
            webView.allowsBackForwardNavigationGestures = true

            webContainerView.addSubview(webView)
            webView.translatesAutoresizingMaskIntoConstraints = false

            let vdict = ["WV": webView!]
            webContainerView.addConstraints(
                NSLayoutConstraint.constraints(withVisualFormat: "H:|[WV]|",
                                               options: [], metrics: nil,
                                               views: vdict)
            )
            webContainerView.addConstraints(
                NSLayoutConstraint.constraints(withVisualFormat: "V:|[WV]|",
                                               options: [], metrics: nil,
                                               views: vdict)
            )

        }
        var urlstr = LoginServer.url.absoluteString
        //#if DEBUG

        let url : URL = URL(string: urlstr)!
        var urlRequest = URLRequest(url: url,
                                    cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData,
                                    timeoutInterval: 60.0)
        if Reachability.shared.isNetworkAvailable(){
            urlRequest.cachePolicy = .reloadRevalidatingCacheData
            _ = webView.load(urlRequest)

        }
        else{
            loadingIndicator.stopAnimating()
            loadingIndicator.isHidden = true
        }

    }

Here is the code for fetch cookies

 func webView(_ webView: WKWebView,
             decidePolicyFor navigationResponse: WKNavigationResponse,
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void)
{

    if let httpResponse = navigationResponse.response as? HTTPURLResponse {
        if let headers = httpResponse.allHeaderFields as? [String: String], let url = httpResponse.url {
            let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: url)

            for cookie in cookies {
                print(cookie.description)
                print("found cookie " + cookie.name + " " + cookie.value)
            }
        }
    }


        decisionHandler(.allow)

}
1
I think you need to be a little more specific and add some code before anyone will be able to help. Read this stackoverflow.com/help/how-to-ask - adamfowlerphoto
@spads let me know what you need more. i guess if you worked on WKWebView. you will understand my bug. - Sri..
how are you creating the wkwebview? how are you accessing the cookies? - adamfowlerphoto
here you go codepaste.net/mbr8ph - Sri..
I was used UIWebView. But on Multiple frame loading my textfield keyboard is resigning. if i use WKWebView. above metioned issue not coming. But on WKWebView im not getting all cookies. - Sri..

1 Answers

-1
votes

You should be able to access all the cookies with the following code

let cookies = HTTPCookieStorage.shared.cookies
for cookie in cookies! {
    print(cookie.description)
    print("found cookie " + cookie.name + " " + cookie.value)
}

Below is a summary of my web view controller

class MyWebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {

    override func viewDidLoad() {
        super.viewDidLoad()

        // create WKWebViewConfiguration
        let webViewConfig = WKWebViewConfiguration()
        let userContentController = WKUserContentController();
        userContentController.add(self, name: "myApp")
        webViewConfig.userContentController = userContentController

        // init and load request in webview.
        webView = WKWebView(frame: self.view.frame, configuration:webViewConfig)
        webView.navigationDelegate = self
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(webView)

        let request = URLRequest(url: webAddress)
        webView.load(request)
    }

    //
    // WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler:@escaping ((WKNavigationActionPolicy) -> Void)) {
        print("decidePolicyForNavigationAction with url:\(String(describing: navigationAction.request.url!))")

        if let url = navigationAction.request.url {
            // url request is outside of my website, then use safari to view address
            if webAddress.host != url.host {
                UIApplication.shared.open(url)
                decisionHandler(.cancel)
            }
        }
        decisionHandler(.allow)
    }

    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationResponse: WKNavigationResponse,
                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void)
    {

        let cookies = HTTPCookieStorage.shared.cookies
        for cookie in cookies! {
            print(cookie.description)
            print("found cookie " + cookie.name + " " + cookie.value)
        }
        decisionHandler(.allow)
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("Navigation error :\(error.localizedDescription)")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("Loading error :\(error.localizedDescription)")
    }

    //
    // WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    }

    var webView: WKWebView!
    var config = ResolveConfig()
    let webAddress = URL(string:"https://mywebaddr.com")!
}