Search code examples
xcode8xctestios-ui-automation

How to wait for Location Alert ( which is system alert) to show?


I figured out how to dismiss System alert, but I am not able to wait for it to show , since app doesn't see System Alerts. I tried to debug with app.debugDescription and app.alerts.count but no luck.


Solution

  • Use addUIInterruptionMonitor:withDescription:handler: to register an interruption monitor. To 'wait' for the system alert to appear, use the handler to set a variable when it has been dealt with, and execute a benign interaction with the app when you want to wait for the alert.

    You must continue to interact with the app while you are waiting, as interactions are what trigger interruption monitors.

    class MyTests: XCTestCase {
    
        let app = XCUIApplication()
    
        func testLocationAlertAppears() {
            var hasDismissedLocationAlert = false
            let monitor = addUIInterruptionMonitor(withDescription: "LocationPermissions") { (alert) in
                // Check this alert is the location alert
                let location = NSPredicate(format: "label CONTAINS 'Location'")
                if alert.staticTexts.element(matching: location).exists {
                    // Dismiss the alert
                    alert.buttons["Allow"].tap()
                    hasDismissedLocationAlert = true
                    return true
                }
                return false
            }
    
            // Wait for location alert to be dismissed
            var i = 0
            while !hasDismissedLocationAlert && i < 20 {
                // Do some benign interaction
                app.tap()
                i += 1
            }
    
            // Clean up
            removeUIInterruptionMonitor(monitor)
    
            // Check location alert was dismissed
            XCTAssertTrue(hasDismissedLocationAlert)
        }
    }