1
votes

I have a Webview of WKWebview where I am loading a URL. The loaded website have a login page and a home page. After login, user is directed to the home page. While logging in, a cookie is sent to the user. I want to get this cookie and at that very moment need to make HTTP call with that. As I am new in iOS, as far I got some information on getting all the cookies at once and for specific url. But 'for specific url' I am not getting the cookie at the right moment and don't know how to get that.

So, the thing is I want to know how to observe that user has logged in and I have got the cookie after logged in.

I have tried some Code:

Observer code in viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(cookiesConfigured(notification:)), name: .cooKieName, object: nil)

webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

Observer method

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


}

Notification handler and cookie getter method

@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)")
        }
    }