Search code examples
swifthtml-parsingwkwebview

Ambigous reference to initializer 'init(_:)' when trying to parse Any? object to String in Swift


I'm trying to parse an Any? object to String which contains an HTML Document that comes from a WKWebView after JS Execution.

If I try to print the Html: Any? object everything shows on console, but when I try to store it in a String var to do another stuff with it, appears the error

Ambigous reference to initializer 'init(_:)'

Here is my code:

func getHTML() {
    miWEBVIEW.evaluateJavaScript("document.documentElement.outerHTML.toString()", completionHandler: { (html: Any?, error: Error?) in
         print(html) // -> This works showing HTML on Console, but need in String to manipulate
         return html            
    })
}

Here is where I call the function in a button event:

let document: Any? = getHTML()
var documentString = String(document) // -> error appears in this line

Solution

  • The problem is that your getTML method returns Void. You can't initialize a String object with it. Besides that WKWebView evaluateJavaScript is an asynchronous method. You need to add a completion handler to your getHTML method:

    func getHTML(completion: @escaping (_ html: Any?, _ error: Error?) -> ()) {
        webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
                                   completionHandler: completion)
    }
    

    Then you need call your getHTML method like this:

    getHTML { html, error in
        guard let html = html as? String, error == nil else { return }
        self.doWhatever(with: html)
    }
    

    func doWhatever(with html: String) {
        print(html)
        // put your code here
    }