Home > Software design >  How to stock a variable even if an app is closed? [Swift]
How to stock a variable even if an app is closed? [Swift]

Time:10-21

so recently I started learning swift and for practicing I wanted to do an homework counter app, It‘s an app that every time you press a button it add to the variable counting 1.

The problem is every time I close the app and open it, the count is reset.

How can I make the variable counting keep its count even if the app is closed?

Here is my code :

import UIKit

var counting = 0

class ViewController: UIViewController {
        
    @IBOutlet weak var label: UILabel!
    
    @IBAction func button(_ sender: Any) {
        counting  = 1
        label.text = "You did \(counting) homeworks"
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
}

Can someone help please?

CodePudding user response:

You can store it in UserDefaults on the phone. However, if they deleted the app, this would be removed as well.

//Declare user defaults

let defaults = UserDefaults.standard

//Set a key

defaults.setValue("text_to_save", forKey: "key_name")

//Retrieve a value by key

let text_to_save = defaults.string(forKey: "key_name")

CodePudding user response:

You can use 'UserDefaults' to store your data(int, string, float, object, etc). It is easy to store.

UserDefaults.standard.set(10, forKey: "MY_AGE")

You can store using keychain. Basically username and password are stored using keychain. Follow this link below.

https://www.codegrepper.com/code-examples/swift/Using keychain to store password and username swift

You also can use core data to store your value. It is a little bit difficult to implement. It's mainly used for offline storage. Follow this link below.

Store Integers in Core Data using Swift and XCode

  • Related