Ios 在Xcode UI测试中,如何反复检查元素是否存在,如果存在,如何执行操作?

Ios 在Xcode UI测试中,如何反复检查元素是否存在,如果存在,如何执行操作?,ios,xcode-ui-testing,Ios,Xcode Ui Testing,我正在实现UI测试。该应用程序进行API调用,可能会显示警报(它是附加到窗口的UIView)。当然,这些都是随机的/不可预测的。如果它们出现,我必须将其排除(单击“关闭”按钮)。你知道怎么做吗?我是否有一些事件表明UI上发生了一些事情?我想有一个线程,每0.5秒执行一次,检查是否存在dismise按钮,如果存在,我点击它 DispatchQueue.global().async { while true { Dispatch

我正在实现UI测试。该应用程序进行API调用,可能会显示警报(它是附加到窗口的UIView)。当然,这些都是随机的/不可预测的。如果它们出现,我必须将其排除(单击“关闭”按钮)。你知道怎么做吗?我是否有一些事件表明UI上发生了一些事情?我想有一个线程,每0.5秒执行一次,检查是否存在dismise按钮,如果存在,我点击它

        DispatchQueue.global().async {
        while true
        {
            DispatchQueue.main.async {
                if(self.app.buttons["NotificationCloseButton"].exists)
                {
                    self.app.buttons["NotificationCloseButton"].tap()
                }
            }
            sleep(5)
        }
    }

问题是它会导致随机崩溃:
属性和返回的错误都没有

有一个很好的例子说明如何等待元素出现在屏幕上。下面是从链接中获取的代码示例:

let nextGame = self.app.staticTexts["Game 4 - Tomorrow"]
let exists = NSPredicate(format: "exists == true")
expectation(for: exists, evaluatedWithObject: nextGame, handler: nil)

app.buttons["Load More Games"].tap()

waitForExpectations(timeout: 5, handler: nil)
XCTAssert(nextGameLabel.exists)
链接还提供了如何等待系统警报出现:

addUIInterruptionMonitor(withDescription: "Location Dialog") { (alert) -> Bool in
    alert.buttons["Allow"].tap()
    return true
}

app.buttons["Find Games Nearby?"].tap()
app.tap() // need to interact with the app for the handler to fire
XCTAssert(app.staticTexts["Authorized"].exists)