我正在尝试(使用XCTest框架)测试驻留在框架内的视图控制器(动态库)。我遇到了属性UIApplication.sharedApplication()。keyWindow的问题,它是nil。我有以下代码:
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: STORYBOARD_NAME_REPORT,
bundle: BundleUtil.getCurrentBundle())
let chatViewController = storyboard.instantiateViewControllerWithIdentifier(VIEW_CONTROLLER_ID_TIP_CHAT) as UIViewController
let navigationController = UINavigationController()
let viewControllers = [chatViewController]
navigationController.viewControllers = viewControllers
// PROBLEM: The following causes a crash because keyWindow is nil.
UIApplication.sharedApplication().keyWindow!.rootViewController = chatViewController
// Force the view controller to be loaded.
// Source: https://www.natashatherobot.com/ios-testing-view-controllers-swift/
let _ = navigationController.view
let _ = chatViewController.view
}
如何使keywindow属性正确初始化?
答案 0 :(得分:0)
您可以尝试如下设置吗:
首先获取共享窗口,然后将视图控制器分配为根控制器
var window = UIApplication.shared.delegate?.window!
window.rootViewController = viewController
,然后使窗口键可见。
window.makeKeyAndVisible()
CATransaction.flush() //optional