Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nicholas poulos
1,291 PointsHow can I measure the time in minutes from when my app was closed to when it was reopened?
How can I measure the time in minutes from when my app was closed to when it was reopened?
I'm basically making a pet-type app and need to determine how long the user has "neglected" the pet for so that it can affect the stat's of the pet.
I'm assuming I'd need to take a time stamp of when the app is closed and then compare it to a fresh timestamp of when it was reopened but I'm having a bit of trouble.
I have tried saving a timestamp as an NSUserDefault but I can't get something to work with.
Any help would be amazing. I'm thinking NSTimeIntervalSince1970 might be useful but there could be a much easier way?
I'm using Swift btw. :)
1 Answer
Steve Hunter
57,712 PointsYou need to use something that persists data - so you can store a timestamp (TimeIntervalSince1970 is fine) in the device rather than in a variable. On reopening the app, the stored value can be compared to "now" to give you your 'closed duration'. I'm guessing the a SQLite database would be the best way of delivering this functionality; indeed SQLite would open up many additional storage options that may be of use for your project.
I don't recall having done this in Swift, unfortunately, although I'm sure the documentation will assist.