以编程方式将应用程序发送到后台

问题描述 投票:12回答:4

有没有办法将应用程序发送到后台?与你如何调用XCUIApplication.terminate()类似,我有一些UI元素来测试applicationDidBecomeActive(_:)。有谁知道这是否可能?

ios swift xcode-ui-testing
4个回答
8
投票

我建议退房XCUIDevice。您可以按下主页按钮,然后重新启动应用程序

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

5
投票

我刚刚成功尝试了UIApplication.sharedApplication().performSelector("suspend")

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

4
投票

在Xcode 9.0中,Apple推出了XCUIApplication.activate()。如有必要,activate()将启动该应用程序,但如果已经运行,则不会终止该应用程序。从而:

func testExample() {
    // Background the app
    XCUIDevice().press(.home)
    // Reactivate the app
    XCUIApplication().launch()
}

0
投票

在我的情况下,我想要背景应用程序,并在我之前离开它的地方打开它。要应用该应用程序:

XCUIDevice.shared.press(.home)

要重新打开我离开它的应用:

XCUIApplication().activate()

使用XCUIApplication().launch()重新启动应用程序将从新推出应用程序。

我使用的是Swift 4.2

© www.soinside.com 2019 - 2024. All rights reserved.