如何在 Swift 中每天只显示一次弹出窗口?

Jkr*_*ist 3 swift

我想在我的应用程序中每天仅显示一次弹出窗口,如果用户已经看到该弹出窗口,那么当天就不再显示它。我挣扎了一段时间,决定在这里寻求一些帮助:)

更新

这是我到目前为止编写的代码:

func showPopupOncePerDay() -> Bool {
    let lastPopup = UserDefaults.standard.double(forKey: "lastPopup")
    let lastPopupDate = Date(timeIntervalSinceNow: lastPopup)
    let lastPopupIsToday = NSCalendar.current.isDateInToday(lastPopupDate)
    if !lastPopupIsToday {
        navigator.showAlertPopup()
    }
    UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: "lastPopup")
    return true
}
Run Code Online (Sandbox Code Playgroud)

Bib*_*cob 5

这是一个简单的解决方案。只需存储您上次Date显示的警报,然后检查该警报是否Date在今天显示或不显示警报。

let lastAlertDateKey = "lastAlertDate"

func checkIfAlertShownToday() {
    if let lastAlertDate = UserDefaults.standard.object(forKey: lastAlertDateKey) as? Date {
        if Calendar.current.isDateInToday(lastAlertDate) {
            print("Alert was shown today!")
        } else {
            showAlert()
        }
    } else {
        showAlert()
    }
}

func showAlert() {
    print("Need to show an alert today!")
    UserDefaults.standard.set(Date(), forKey: lastAlertDateKey)
    navigator.showAlertPopup()
}
Run Code Online (Sandbox Code Playgroud)