以编程方式将应用程序发送到后台
Programmatically sending an app to background
有没有办法将应用程序发送到后台?与调用 XCUIApplication.terminate()
的方式类似,我有一些 UI 元素要在 applicationDidBecomeActive(_:)
上测试。有谁知道这是否可能?
我刚试了 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"))
我建议查看 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)
}
在 Xcode 9.0 中,Apple 引入了 XCUIApplication.activate()
。 activate()
将在必要时启动应用程序,但如果已经 运行 则不会终止它。因此:
func testExample() {
// Background the app
XCUIDevice().press(.home)
// Reactivate the app
XCUIApplication().launch()
}
在我的例子中,我想将应用设置为后台并在我之前离开的地方打开它。为应用设置背景:
XCUIDevice.shared.press(.home)
重新打开我离开的应用程序:
XCUIApplication().activate()
使用 XCUIApplication().launch()
重新启动应用将从新启动应用。
我用的是Swift4.2
有没有办法将应用程序发送到后台?与调用 XCUIApplication.terminate()
的方式类似,我有一些 UI 元素要在 applicationDidBecomeActive(_:)
上测试。有谁知道这是否可能?
我刚试了 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"))
我建议查看 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)
}
在 Xcode 9.0 中,Apple 引入了 XCUIApplication.activate()
。 activate()
将在必要时启动应用程序,但如果已经 运行 则不会终止它。因此:
func testExample() {
// Background the app
XCUIDevice().press(.home)
// Reactivate the app
XCUIApplication().launch()
}
在我的例子中,我想将应用设置为后台并在我之前离开的地方打开它。为应用设置背景:
XCUIDevice.shared.press(.home)
重新打开我离开的应用程序:
XCUIApplication().activate()
使用 XCUIApplication().launch()
重新启动应用将从新启动应用。
我用的是Swift4.2