Programmatically sending an app to background

元气小坏坏 提交于 2019-11-28 09:57:25
JMFR

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

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!