Programmatically sending an app to background

前端 未结 4 1790

Is there a way to send the application to background? Similarly to how you can call XCUIApplication.terminate(), I have some UI Elements to test on applic

相关标签:
4条回答
  • 2020-12-10 04:45

    In my case I wanted to background the app and open it where I previously left it. To background the app:

    XCUIDevice.shared.press(.home)
    

    To re-open the app where I left it:

    XCUIApplication().activate()
    

    Re-launching the app using XCUIApplication().launch() would launch the app from new.

    I am using Swift 4.2

    0 讨论(0)
  • 2020-12-10 05:00

    In Xcode 9.0, Apple introduced XCUIApplication.activate(). activate() will launch the application if necessary, but will not terminate it if it is already running. Thus:

    func testExample() {
        // Background the app
        XCUIDevice().press(.home)
        // Reactivate the app
        XCUIApplication().launch()
    }
    
    0 讨论(0)
  • 2020-12-10 05:02

    I would recommend checking out XCUIDevice. Here is how you might press the home button and then relaunch the application

    func testExample() {
    
        // Has a nav bar.
        XCTAssert(XCUIApplication().navigationBars.element.exists)
    
        XCUIDevice().press(XCUIDeviceButton.home)
        // Before Swift 3: XCUIDevice().pressButton(XCUIDeviceButton.Home)
        XCUIApplication().launch()
    
        // Navigationbar still there on second launch.
        XCTAssert(XCUIApplication().navigationBars.element.exists)
    }
    
    0 讨论(0)
  • 2020-12-10 05:06

    I just tried UIApplication.sharedApplication().performSelector("suspend") successfully.

    dispatch_after(2, dispatch_get_main_queue(), {       
        // suspend the app after two seconds
        UIApplication.sharedApplication().performSelector("suspend")
    })
    
    // Swift 4 version
    UIApplication.shared.perform(Selector("suspend"))
    
    0 讨论(0)
提交回复
热议问题