Here is some sample code, how can u use NSUserDefaults
to do something like you described.
You need the value stored by an identifier in NSUserDefaults
, easiest is as an integer
.
Whenever you call increaseViewLoadedCount()
, it will increase the counter's value, e.g. a view has been loaded.
Whenever you call shouldShowAlert()
, we read the value from defaults, check it against some value, and return a boolean
based on that.
Also, the NSUserdefaults
are being synchronised, therefore even if the app is terminated, the counter value will be kept.
extension UserDefaults {
/// Indetifier of counter container in `defaults`
private static let kCounterIdentifier = "counter"
/// Count of loads after the alert should not be loaded
private static let notDisplayAlertAfterCount = 3
/// Increase the counter value
func increaseViewLoadedCount() {
guard let counterValue = value(forKey: UserDefaults.kCounterIdentifier) as? Int else {
syncronizeCounter(with: 1)
return
}
syncronizeCounter(with: counterValue + 1)
}
/// Reset the value to zero in Userdaults
func resetViewLoadedCount() {
syncronizeCounter(with: 0)
}
/// Check weather the alert should be presented or not
///
/// - Returns: true if counter is smaller than notDisplayAlertAfterCount, false if greater
func shouldShowAlert() -> Bool {
guard let counterValue = value(forKey: UserDefaults.kCounterIdentifier) as? Int else {
return true
}
// Set the number anything you like
return counterValue < UserDefaults.notDisplayAlertAfterCount ? true : false
}
private func syncronizeCounter(with value: Int) {
set(value, forKey: UserDefaults.kCounterIdentifier)
synchronize()
}
}
Test:
print(defaults.shouldShowAlert()) // prints true
defaults.increaseViewLoadedCount()
defaults.increaseViewLoadedCount()
print(defaults.shouldShowAlert()) // prints true
defaults.increaseViewLoadedCount()
print(defaults.shouldShowAlert()) // prints false