Probably the DOM Element was not ready yet when you tried to access it. You should move your code to didFinish method of WKNavigationDelegate protocol.
So your UIViewController should look like this:
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad(){
super.viewDidLoad()
...
webBrowser.navigationDelegate = self
webBrowser.load(request)
...
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementsByClassName('siteName').length") { (value, error) in
print("LENGTH IS ", value)
print("ERROR IS ", error)
let jsValue = value as? Int
if jsValue == 0{
self.waitClick()
} else {
self.startItemColor()
}
}
}
}
Also don't forget to enable App Transport Security in your info.plist like this
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
In case this doesn't work try to debug why. Probably try to call a method in your JavaScript that returns the length of class="sitename" element and also that console.log(length) so that you can go further in debugging and see what's going on.