I would like to count how many continuous days user has used the app.
It updates the label depending on the streaks and if user has not used the app for a day the number goes back to zero.
How can I achieve this? I have searched but could not find any source.
Your app idea may include the need to perform some actions before considering a complete usage. For example, after loading or presenting something on the screen, after retrieving data and performing some actions, etc.
Just by intention of opening the app. The only intention is for the user to hit your app´s icon to launch the app, nevermind if he set it to a close state before even passing your loading screen.
This can be a bit unpredictable
Important to notice that iOS can kill your process anytime after your app is sent to background, so better to do it right after user´s action.
Also, the user could not open your app again in a while.
You can subscribe to background capabilities for letting your app be active for a while longer while transitioning to suspended/close state if you are going to save data out of the iPhone.
The function you are looking for is applicationDidEnterBackground(_:)
Strong Points of this approach
You get last time that your app was actually used.
For more on the application life cycle and how to handle it correctly, please visit apple documentation about this topic
NSUserDefaults
. In this case you should implement some kind of online storage, via user creation & handling in your servers or the use of iCloud alternatives.NSUserDefaults
, as it is not encripted and can be modified.Simplicity is king when dealing with stored data and there are many ways to achieve this specific task.
I would go with:
You could save complete timestamp in order to be able of change your mind later ;-)
In my app I would do the maths then with current date data (now = NSDate()
) before making any changes.
now
and last visit date
is bigger than
a "Day", then update first visit date
with now
. now
data into last visit date
storage.Your counter will always be the difference in "Days" between
now
andfirst visit date
.
If your data is not sensitive store it in NSUserDefaults
, otherwise and if this can affect your income store it somewhere else. If it's sensitive but you don't care if your user lose the counter, save it in a local DB (CoreData, Realm, etc)
Best time (as of my consideration) for storing new data will be when an intention of closure (included suspended state and incoming calls) is notified to your app.
You can save this data in many ways, one that give you some space for maneuvering is saving just last visit and date of first visit of the row and then do the maths. Of course, updating as needed and explained before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With