如何检测UI元素存在性且避免触发查询超时报错?
UI元素检测避免超时报错的解决方案
问题描述
尝试查询某个UI元素时,若元素不存在会触发报错:
Failed to get matching snapshots: Timed out while evaluating UI query.
当前使用的检测代码:
let account_number = applePayUI.buttons["Wallet.BankConnectAccountCredentialsView.AccountNumber"] if account_number.exists { state = PAYMENT } else { state = NO_PAYMENT }
需要实现仅检测元素是否存在,不触发上述超时报错。
可行方案
1. 短超时查询单个元素
使用带自定义短超时的查询方法,让元素不存在时快速返回结果而非抛出错误:
let accountButton = applePayUI.buttons.matching(identifier: "Wallet.BankConnectAccountCredentialsView.AccountNumber").firstMatch(withTimeout: 0.3) state = accountButton.exists ? PAYMENT : NO_PAYMENT
设置极短超时(比如0.3秒),既能保证元素存在时被检测到,又不会因元素不存在触发超时报错。
2. 捕获错误处理
将查询逻辑包裹在do-catch块中,捕获超时相关错误,统一处理为元素不存在的情况:
var state = NO_PAYMENT do { let account_number = try applePayUI.buttons["Wallet.BankConnectAccountCredentialsView.AccountNumber"].waitForExistence(timeout: 0.5) if account_number.exists { state = PAYMENT } } catch { // 捕获超时或元素不存在的错误,保持state为NO_PAYMENT }
3. 检查元素集合数量
先获取所有匹配的元素集合,通过判断集合是否为空来确定元素是否存在,避免直接访问单个元素触发的超时:
let accountButtons = applePayUI.buttons.matching(identifier: "Wallet.BankConnectAccountCredentialsView.AccountNumber") state = accountButtons.count > 0 ? PAYMENT : NO_PAYMENT
内容的提问来源于stack exchange,提问作者Chao Xu
相关产品推荐
相关产品推荐

