I am trying to add a timer for when a user clicks a button it starts a timer for 24 hours and disables the button for the next 24 hours. After that it is enabled again. There is a few answers out there for things similar but not 100% useful for doing it in SWIFT.
The main problem I am having is that I want this to be specific for each user. So 24 hours for every click on that one user. So for example: If I 'like' something then you want be able to 'like' that particular thing again for 24 hours but can still 'like' a different thing?
Thanks
You can do it by setting the actual date
+ 1 day
and save it into yourNSUserDefaults
:.So in your button-pressed method, you can do something like that:
And to check the time you can retrieve the information. I would recommend to check it inside the
AppDelegate
methods likeapplicationDidFinishLaunchingWithOptions
.*
Works for Swift 3
*
I have a daily video Ad that my users can view to get extra cash. This is what I use to ensure they can only view it once a day.
1.) Create a function that will be called when the user triggers it.
2.) Create a variable at the top of your file.
3.) In the
viewDidLoad
ordidMoveToView
call:A few things to consider first.
How important is it that this button can not be subverted?
If you are depending on the device for its current time and date, then the user can always just move that forward one day in the device settings.
Do you want any behavior to happen outside of your application?
should the user be notified that the button is now enabled
Assuming you don't need strictly enforce the 24 hour period, and you don't want to notify the user (they can find out when they return to your app), then you have only to do a few things.
Get a timeStamp when the button is pressed, start an NSTimer for 24Hours, and save the timeStamp to NSUserDefaults.
Now if the user never leaves your app, your good. In real life they will, so you will need to check when you re-enter your app if you need to disable the button, based on the timeStamp and start a new timer for the amount of time that is left.