Search code examples
swiftviewcontrollersavensuserdefaults

Open in same view controller as closed on (swift)


I am making a simple fact app (In swift) and all the facts are in separate view controllers and when the user closes the app, it all goes to the main page and you have to start from fact 1 again.

I want to know how to save what view controller the user was on when they closed it and when they continue through the facts again,it starts on that fact. Thanks:) also if someone makes a video i think it will get enough views to start a YT channel


Solution

  • Updated to Swift 5

    You can use UserDefaults which will remember your last ViewController.

    First of all, you have to store some integer when you load any view like shown below:

    FirstView.swift

     override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.setValue(0, forKey: "View")
        // Do any additional setup after loading the view, typically from a nib.
    }
    

    SecondViewController.swift

    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.setValue(1, forKey: "View")
        // Do any additional setup after loading the view.
    }
    

    Now In your AppDelegate.swift read that stored values and load the ViewController related to that Integer this way:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        let viewCount = UserDefaults.standard.integer(forKey: "View")
        var VC = UIViewController()
        let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        println(viewCount)
        if viewCount == 0 {
            //FirstView should initiate
            VC = storyboard.instantiateViewController(withIdentifier: "First") as! ViewController
        } else if viewCount == 1 {
            //SecondView should inititate
            VC = storyboard.instantiateViewController(withIdentifier: "Second") as! SecondViewController
        } else {
            //ThirdView Should Initiate
            VC = storyboard.instantiateViewController(withIdentifier: "Third") as! ThirdViewController
        }
    
        self.window?.makeKeyAndVisible()
        self.window?.rootViewController = VC
    
        return true
    }
    

    Check out THIS sample project for more Info.