简体   繁体   English

使用NSUserDefaults在SWIFT中添加24小时倒数计时器

[英]Using NSUserDefaults to add a 24hour countdown timer in SWIFT

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. 我试图为用户单击按钮添加一个计时器,它将在24小时内启动计时器,并在接下来的24小时内禁用该按钮。 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. 对于类似的事情,这里有一些答案,但对于在SWIFT中做到这一点并非100%有用。

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. 因此,该用户的每次点击都需要24小时。 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? 因此,例如:如果我“喜欢”某件东西,那么您希望能够在24小时内再次“喜欢”该特定东西,但仍然可以“喜欢”另一件东西?

Thanks 谢谢

* *

Works for Swift 3 适用于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. 1.)创建一个将在用户触发时调用的函数。

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. 2.)在文件顶部创建一个变量。

let todaysDate = NSDate()

3.) In the viewDidLoad or didMoveToView call: 3.)在viewDidLoaddidMoveToView调用中:

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")

        }
    }

You can do it by setting the actual date + 1 day and save it into your NSUserDefaults :. 您可以通过设置实际日期+ 1 day并将其保存到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 AppDelegate methods like applicationDidFinishLaunchingWithOptions . 我建议在诸如applicationDidFinishLaunchingWithOptions类的AppDelegate方法中检查它。

//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
    }
}

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. 假设您不需要严格执行24小时周期,并且您不想通知用户(他们可以在用户返回到您的应用时知道它们),那么您只需做几件事。

Get a timeStamp when the button is pressed, start an NSTimer for 24Hours, and save the timeStamp to NSUserDefaults. 按下按钮时获取时间戳,启动NSTimer 24小时,然后将时间戳保存到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. 在现实生活中,它们将如此,因此您需要根据timeStamp检查是否需要禁用按钮时重新进入应用程序的时间,并为剩余的时间启动一个新计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM