首页 > 解决方案 > 在后台一段时间后将应用程序带到前台时,iOS黑屏

问题描述

我正在尝试从我们的 iOS 应用程序中删除所有故事板,因为在与 Git 团队合作时它们会变得一团糟。

我现在在 AppDelegate 的application(_:didFinishLaunchingWithOptions:)方法中设置初始 ViewController:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    let launchViewController = LaunchView()
    window!.rootViewController = launchViewController
    window!.makeKeyAndVisible()

    [...]

    return true
}

LaunchView 是一个简单的视图控制器,负责将用户路由到登录或主屏幕,具体取决于他/她是否登录。

在此之前,LaunchView 在Main.storyboard.

我已经从Info.plist文件中删除了这些行:

<key>UIMainStoryboardFile</key>
<string>Main</string>

一切正常,除了当我们将应用程序留在后台几个小时而没有强制退出它(我不确定重现此需要多少时间)然后将应用程序带回前台,全黑屏幕显示,好像根控制器消失了。我们必须杀死该应用程序并重新打开它才能使用它。

这让我发疯,因为它真的很难重现,因为如果你只将应用程序留在后台几分钟,它就可以正常工作。我怀疑它与应用程序暂停状态有关,但我不太确定。

你知道问题可能出在哪里吗?

谢谢!

编辑

也许这与问题有关:在 LaunchView 上,我使用以下代码将用户发送到主屏幕(如果他已登录):

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

let rootVC = UIStoryboard.main.rootViewController
if let snapshot = appDelegate.window?.snapshotView(afterScreenUpdates: true) {

    rootVC.view.addSubview(snapshot);
    appDelegate.window?.rootViewController = rootVC

    UIView.transition(with: snapshot, duration: 0.4, options: .transitionCrossDissolve, animations: {
        snapshot.layer.opacity = 0;
    }, completion: { (status) in
        snapshot.removeFromSuperview()
    })
}
else {
    appDelegate.window?.rootViewController = rootVC
}

iOS 是否有可能在某个时候删除 rootViewController?

标签: iosswiftbackgroundforeground

解决方案


window原来问题与交换's时涉及快照的过渡效果有关rootViewController

我删除了过渡效果并简单地更改了rootViewController. 现在它工作正常!

在代码中,我改变了这个:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

let rootVC = UIStoryboard.main.rootViewController
if let snapshot = appDelegate.window?.snapshotView(afterScreenUpdates: true) {

    rootVC.view.addSubview(snapshot);
    appDelegate.window?.rootViewController = rootVC

    UIView.transition(with: snapshot, duration: 0.4, options: .transitionCrossDissolve, animations: {
        snapshot.layer.opacity = 0;
    }, completion: { (status) in
        snapshot.removeFromSuperview()
    })
}
else {
    appDelegate.window?.rootViewController = rootVC
}

对此:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let rootVC = UIStoryboard.main.rootViewController
appDelegate.window?.rootViewController = rootVC

感谢大家的帮助!我希望这个答案对其他人有用。


推荐阅读