THIS ARTICLE IS NOT ABOUT TESTING WEBSITES WITH XCUITEST. I think that can be done, but I don’t do it, it sounds terribly painful, and there are probably better tools available.

This article is to help you with a very common question I see asked on the StackOverflow XCUITest tag. “How do I ensure my app has sent me to the correct URL when I tap a link inside it?” Coincidentally, I’m mentoring a couple of folks at work, one was faced with this question, and his best hit was my answer ?

As you can see in that answer, it’s fairly straightforward to get the URL:

    1. “Activate” Safari – let app = XCUIApplication(bundleIdentifier: "")
    2. The URL field is initially a button we can’t do much with other than tap – app.buttons["URL"].tap()
    3. After tapping, the URL field becomes a text field and you can grab its value – app.textFields["URL"].value as! String

But there is a major pitfall! Unless you are running against a perfectly reliably web server and never perform redirects, this can be flaky; XCUITest doesn’t know how to wait for a page to load, which means if you do your check while things are loading you’ll get erroneous data.

How can we wait for a page to load? That was tricky, but with some speedy debugging (had to grab the app’s contents while it was loading) I was able to discover there is a loading text (invisible to the user) in the background that presumably provides the loading status to screen readers. Once the page has loaded, it disappears. We’ve got our key!

That magical bit of text lives under the URL button at app.buttons["URL].otherElements.firstMatch and by waiting for it to not contain the % symbol (using my preferred Timer pattern – this link actually doesn’t go into much depth on the usage for XCUITest so ?there’s an article idea for me!), we can ensure the page has fully loaded and you’ll get the correct URL value.

Happy and reliable URL checking!