简体   繁体   中英

How can I make my app pop to a VC when the app enters the background?

I've been trying for a while now to figure out how to make my app pop back to my initialVC when the user leaves the app so that when they come back, the view that opens is the home page and not the view they left off with. This code is what I put in my appDelegate file. Right now I'm getting an error saying use of unresolved identifier 'presentViewController' Please note that my app has one main VC (embedded in a navigation controller), which has 2 buttons that lead each to one different tableViewController (both of them also embedded in a navigation controller).

func applicationDidEnterBackground(application: UIApplication) {

    var storyboard = UIStoryboard(name: "MainStoryboard", bundle: NSBundle.mainBundle())

    if let myVC = storyboard.instantiateViewControllerWithIdentifier("Home") as? ViewController {
        presentViewController(myVC, animated: true, completion: nil)
    }

}

You could change your RootViewController when going to background or when coming to foreground.

let storyBoard = UIStoryboard(name: "Main", bundle: nil)
if let controller =  storyBoard.instantiateViewControllerWithIdentifier("") as? UIViewController {
self.window?.rootViewController = controller
}

You should not be attempting this behavior in the iOS world as it's grounds for possible rejection. Per apple's guidelines:

Save the current state when stopping at the finest level of detail possible. In this way, people don't lose their context when they switch back to your app. For example, if your app displays scrolling data, save the current scroll position. You can learn more about efficient ways to preserve and restore your app's state in Preserving Your App's Visual Appearance Across Launches in App Programming Guide for iOS.

Apple Human Interface Guidelines

Perhaps the best solution is to not allow the app to run in background. That way, each time the user launches your app, it will start fresh.

You can't present a view controller from the app delegate, thus the error.

But nevertheless, if you want to pop to your initial view controller (ie the "root view controller"), and you're using a UINavigationController , you can do it like so:

func applicationDidEnterBackground(application: UIApplication) {

    var navigationController = application.windows[0].rootViewController as UINavigationController

    navigationController.popToRootViewControllerAnimated(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM