【问题标题】:Date comparison always returns true - Swift日期比较总是返回 true - Swift
【发布时间】:2021-09-20 19:37:53
【问题描述】:

我想跟踪用户上次刷新 api 的时间,所以我决定这样做:

@AppStorage("lastTimeUserRefreshedApi") var lastTimeUserRefreshedApi: Date = Date()

func canUserRefreshAPI() -> Bool {
    let readyToBeRefreshed: Date = lastTimeUserRefreshedApi.addingTimeInterval(5) // in seconds
    let currentTime: Date = Date()
    var canUserRefresh: Bool = false
    
    if(currentTime > readyToBeRefreshed) {
        canUserRefresh = true
        lastTimeUserRefreshedApi = lastTimeUserRefreshedApi.addingTimeInterval(5)
    } else {
        canUserRefresh = false
    }
    
    return canUserRefresh
}

问题是它总是返回 true,但是为什么呢?还有更简单的方法吗?

谢谢

编辑:

这是我用来在@AppStorage 中存储日期的扩展:

extension Date: RawRepresentable {
    public var rawValue: String {
        self.timeIntervalSinceReferenceDate.description
    }
    
    public init?(rawValue: String) {
        self = Date(timeIntervalSinceReferenceDate: Double(rawValue) ?? 0.0)
    }
}

【问题讨论】:

  • 当您检查currentTimereadyToBeRefreshed 的值时,调试器会告诉您什么?
  • @jnpdx 检查
  • @Albert 你想每五秒刷新一次吗?
  • 您应该在当前时间上增加 5 秒,而不是在 lastTimeUserRefreshedApi 上增加
  • @LeoDabus 是的,不确定您是否正在考虑使用计时器,但我尝试使用计时器,但问题是当用户第二天从后台返回并想要刷新时,他/她必须等到那个时候,这不适用。所以我想存储时间戳

标签: swift date


【解决方案1】:

你做的比它应该做的要困难得多。只需保存“到期”日期即可。当你阅读它时,只需比较它是否过去。

@AppStorage("expiration")
var expiration: Date = Date(timeIntervalSinceNow: 5)

func canUserRefreshAPI() -> Bool {
    let now = Date()
    if expiration < now {
        expiration = Date(timeIntervalSinceNow: 5)
        return true
    } else {
        return false
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多