Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restart an application programmatically in Swift 4 on iOS?

Tags:

ios

swift

I have issues. After language changing, I want to restart my application.

So I want to get an alert message with the text "Do you want to restart app to change language?" "Yes" "No"

And if the user presses YES, how can I restart the app?

My solution:

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)

After the app will close, the user will manually start the app.

like image 305
Andrew Avatar asked Nov 30 '22 21:11

Andrew


1 Answers

You cannot restart an iOS app. One thing you could do is to pop to your 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
    })
}

In one of my apps, I needed to restart. I wrapped all of the loading logic into a LaunchScreenViewController. Above is the piece of code for "restarting the app".

like image 70
Arthur Avatar answered Dec 09 '22 17:12

Arthur