Berk Eylen
Berk Eylen

Reputation: 29

Save string variable after app close swift iOS

class LoginViewController: UIViewController {

       @objc func handleLogin(){
               let mainTableVC = MainTableViewController()
               mainTableVC.chipInfoString = self.chipField.text
               let navController = UINavigationController(rootViewController: mainTableVC)

               self.present(navController, animated: true, completion: {

                        })
}

class MainTableViewController: UITableViewController {

        var chipInfoString:String?

        let ref = Database.database().reference().child(chipInfoString!)
}

After logging in, MainTableViewController opens. I get chipInfoString from LoginViewController. After closing the application I want the chipInfoString(MainTableViewController) value to get registered.

Upvotes: 0

Views: 588

Answers (1)

ISS
ISS

Reputation: 416

I can give you an example with UserDefaults. Have these functions in the ViewController class or where you need them. For those who are not already familiar UserDefaults can store data on device. It is not a DB tho...

    override func viewDidLayoutSubviews() {
        storeValue()
    }

    override func viewWillAppear(_ animated: Bool) {
        recallValue()
    }


    func storeValue(){
        UserDefaults.standard.set(wage.text!, forKey: "wage")

        // UserDefaults.standard.synchronize() - obsolete, might need to check documentation 
    }

    func recallValue(){
        wage.text! = UserDefaults.standard.string(forKey: "wage")!

    }

On changes, the string will be stored and restored upon app restart. Hope it works!

Upvotes: 1

Related Questions