Programmatically sending an app to background

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


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)
}