skip to Main Content

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?

2

Answers


  1. 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")
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search