Using NSUserDefaults to add a 24hour countdown timer in SWIFT

我怕爱的太早我们不能终老 提交于 2020-01-23 20:57:45

问题


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


回答1:


You can do it by setting the actual date + 1 day and save it into your NSUserDefaults:.

So in your button-pressed method, you can do something like that:

//user pressed button:
func buttonPressed(){
    //current date
    let currentDate = NSDate()
    let calendar = NSCalendar.currentCalendar()

    //add 1 day to the date:
    let newDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: 1, toDate: currentDate, options: NSCalendarOptions.allZeros)

    NSUserDefaults.standardUserDefaults().setValue(newDate, forKey: "waitingDate")

    //disable the button
}

And to check the time you can retrieve the information. I would recommend to check it inside the AppDelegatemethods like applicationDidFinishLaunchingWithOptions.

//call it whereever you want to check if the time is over
if let waitingDate:NSDate = NSUserDefaults.standardUserDefaults().valueForKey("waitingDate") as? NSDate{
    let currentDate = NSDate()
    //If currentDate is after the set date
    if(currentDate.compare(waitingDate) == NSComparisonResult.OrderedDescending){
        //reenable button
    }
}



回答2:


*

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.

func set24HrTimer() {
    let currentDate = NSDate()
    let newDate = NSDate(timeInterval: 86400, since: currentDate as Date)

    UserDefaults.standard.setValue(newDate, forKey: "waitingDate")
    print("24 hours started")

    //disable the button

}

2.) Create a variable at the top of your file.

let todaysDate = NSDate()

3.) In the viewDidLoad or didMoveToView call:

if let waitingDate:NSDate = UserDefaults.standard.value(forKey: "waitingDate") as? NSDate {
        if (todaysDate.compare(waitingDate as Date) == ComparisonResult.orderedDescending) {
            print("show button")

        }
        else {
            print("hide button")

        }
    }



回答3:


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.

//Assuming you have a method named enableButton on self 
let timer = NSTimer.scheduledTimerWithTimeInterval(86400, target: self, selector: "enableButton", userInfo: nil, repeats: false)
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "timeStamp")

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.



来源:https://stackoverflow.com/questions/28571194/using-nsuserdefaults-to-add-a-24hour-countdown-timer-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!