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
You can store it in
UserDefaults
on the phone. However, if they deleted the app, this would be removed as well.You can use ‘UserDefaults’ to store your data(int, string, float, object, etc). It is easy to store.
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