ios - 比较 Swift 中的日期

标签 ios swift

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

已关闭 8 年前

我正在开发我的第一个应用程序。我正在使用 swift 。用户每天只允许执行一次特定操作。我需要编写正确的代码来检查用户今天是否已经采取了操作。不幸的是我几乎不知道如何构建代码。特别是我不知道如何为那些第一次开始使用该应用程序的用户声明带有 nil 的变量。

@IBAction func yesButtonPressed(sender: AnyObject) {

// check if the user have already clicked 'yes' button today
// if true then do some something
// else show the alert

}

非常感谢您的回答!

最佳答案

这并不是非常复杂,但是如果您还没有的话,您将需要学习一些技巧。我会尝试用代码来解释。

您可以使用标准用户默认值来保存某些值,以便即使用户关闭应用程序,它也会保留。

// To get current date and time
let currentDate = NSDate()

// To save it to user defaults - do this when the user presses the button
NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "myDate")
NSUserDefaults.standardUserDefaults().synchronize()

// To retrieve the date from user defaults - and to check if the button was pressed
let myDate = NSUserDefaults.standardUserDefaults().objectForKey("myDate") as? NSDate

// myDate will be nil if it was not set yet (first use). Let's check it for nil
if let lastPushedDate = myDate {

    // get current date a time to compare with the saved value
    let dateNow = NSDate()
    let secondsInADay: NSTimeInterval = 3600 * 25

    // check how many seconds elapsed since last date and do something if the interval is long enough
    if dateNow.timeIntervalSinceDate(lastPushedDate) >= secondsInADay {
        println("We are fine, button can be pushed")
    }
}

因此,在您的函数 yesButtonPressed 中,您需要执行以下操作:

  • 从用户默认值中检索日期。
  • 如果从未使用过,则为零。
  • 如果使用过,则与当前时间进行比较,判断耗时间隔是否足够长。
  • 按下按钮后,将当前日期保存为用户默认值
  • 下一步,为了获得更好的用户体验,您可能希望在时间未到时禁用该按钮,并且仅在可以按下按钮时才启用它。

关于ios - 比较 Swift 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27090071/

上一篇:ios - Swift 中的委托(delegate)错误

下一篇:iOS Autolayout 常量问题导致 UIView 在 iPad 中不占据整个宽度

相关文章:

ios - 新表格 View 单元格显示为空白单元格

swift - 无法更改对象的协议(protocol)一致性

ios - 如何在 iPad 上隐藏快速输入键盘工具栏?

objective-c - 应用程序在 iPhone 5 上崩溃

ios - 我需要两个计时器在同一个 View Controller ios 中工作

ios - UIButton 图像在 tableviewcell 中被扭曲

ios 8自定义键盘在设置页面更改语言

ios - 快速创建一个只有两个圆角的矩形?

ios - 弹出到上一个 View 的问题(导航 Controller )

ios - 使用 WebKit 加载 YouTube 视频时控制台中打印警告