首页 > 解决方案 > 如何在 iOS 上的 Swift 4 中以编程方式重新启动应用程序?

问题描述

我有问题。更改语言后,我想重新启动我的应用程序。

所以我想收到一条带有文本“你想重新启动应用程序以更改语言吗? ”“”“”的警报消息

如果用户按下是,我该如何重新启动应用程序?

我的解决方案:

let alertController = UIAlertController(title: "Language".localized(), message: "To changing language you need to restart application, do you want to restart?".localized(), preferredStyle: .alert)
let okAction = UIAlertAction(title: "Yes".localized(), style: UIAlertActionStyle.default) {
    UIAlertAction in
    NSLog("OK Pressed")
    exit(0)
}

let cancelAction = UIAlertAction(title: "Restart later".localized(), style: UIAlertActionStyle.cancel) {
    UIAlertAction in
    NSLog("Cancel Pressed")
}

alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)

应用程序关闭后,用户将手动启动应用程序。

标签: iosswift

解决方案


您无法重新启动 iOS 应用程序。您可以做的一件事是弹出到您的 rootViewController。

func restartApplication () {
    let viewController = LaunchScreenViewController()
    let navCtrl = UINavigationController(rootViewController: viewController)

    guard
        let window = UIApplication.shared.keyWindow,
        let rootViewController = window.rootViewController

    else {
        return
    }

    navCtrl.view.frame = rootViewController.view.frame
    navCtrl.view.layoutIfNeeded()

    UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: {
        window.rootViewController = navCtrl
    })
}

在我的一个应用程序中,我需要重新启动。我将所有加载逻辑包装到 LaunchScreenViewController 中。以上是“重启应用”的一段代码。


推荐阅读