Search code examples
ioswkwebviewuitestwebviewdidfinishload

How to check if wkwebview finished loading in UItest


I want to take a screenshot of the app when it loads a html file. However sometimes the wkwebview takes a long time to load the html file.

Currently I have to use sleep(5) to wait for the wkwebview to finish loading.

//uitest.swift

sleep(5)
takeScreenshot()

Is there any way to check if wkwebview finished loading in UItest?


Solution

  • I had some problems trying to figure out how to make it too, so I decide to use this work around. In the wkwebview didfinishload if you have any variable there, you can check if it exists or its value. If you do not have any variable there, you must create it in global scope, right? For example if we have this code when wkwebview ends loading:

    func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
       myTopLabel.text = "Content Loaded"
       print("loaded") 
    }
    

    'myTopLabel' is a UILabel that I use to show the status of my web, so what I had to do is execute this command in UITest:

    let nextGameLabel = self.app.staticTexts["Content Loaded"]
    app.buttons["Reload Web"].tap()
    XCTAssert(nextGameLabel.waitForExistence(timeout: 5))
    

    So When I press the app button, the UITest waits for 5 seconds to see if the web is loaded or not. Hope it helps dude.