So I a countdown timer for a task, and I want to know if there is a way to store the time that has elapsed so that it can be recorded in the app. So for example evertyime you used the countdown timer you would store the time that the countdown was running as a lifetime value.
If this exact set of instructions was repeated the total lifetime value would be 11 minutes.
If anyone can point me in the direction of a resource that would explain how to implement such functionality this would be greatly appreciated.
You have several options available to you for persisting a number like that - the absolute easiest and quickest is probably just to use UserDefaults
to store/retrieve the number. That is not exactly the intended use for UserDefaults
, but if you're just storing one TimeInterval
it's not going to cause you any problems.
A bare bones implementation would look like this:
let interval: TimeInterval = 20 //replace with the time from your countdown timer
UserDefaults.standard.set(interval, forKey: "totalTimeElapsed")
And since you need to add the new time to the existing elapsed time, you would do something like this:
let newTimeElapsed: TimeInterval = 20 //replace with time from countdown timer
let totalSoFar = UserDefaults.standard.double(forKey: "totalTimeElapsed") //will be 0 if it doesn't exist
UserDefaults.standard.set(newTimeElapsed + totalSoFar, forKey: "totalTimeElapsed")
Other standard ways you could do this would be NSKeyedArchiver
or Core Data
, though Core Data
would be major overkill for persisting 1 number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.