0

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?

Japanian
  • 3
  • 2
  • I think you're new to computer science. There're memory and disk storage. You can access data in memory instantly but it only live in short time. If you want to store it forever use disk storage. Write your in-memory data to disk, then you can access it anytime later. For storage on iOS, there're lot of techniques: UserDefault, CoreData, SQLite or even raw file... please learn those parts first. – Quang Hà Oct 21 '21 at 05:10
  • read on application life cycle. onviewDidload you retire data, and onViewWillDisappear toy save data to local storage. – Sathya Baman Oct 21 '21 at 05:39

2 Answers2

0

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")
Torewin
  • 887
  • 8
  • 22
0

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

AMIT
  • 906
  • 1
  • 8
  • 20