【问题标题】:Trying to Save My Timer to UserDefaults When The App Gets "Killed"当应用程序被“杀死”时,尝试将我的计时器保存到 UserDefaults
【发布时间】:2019-11-05 06:53:21
【问题描述】:

这是一个计时器应用程序,我希望计时器在应用程序被终止时暂停,当您重新打开应用程序时,我希望计时器显示最后一次已知时间。

我已经为要保存的数据设置了一个结构。

let defaults = UserDefaults.standard    
private enum TimeData {
    static let allCurrentTime = "allCurrentTime"
}

override func viewDidLoad() {
    super.viewDidLoad()

    checkForSavedTimer()
    marksSavedData()
    theTimer.text = "00:00:00"
    theTimer.font = UIFont(name: "Menlo-BoldItalic", size: 40)
    marksTableView.isHidden = false
}


//I set the timer info to the struct (see below)

@objc func updateTimerLabel() {
    seconds += 1

    if seconds == 60 {
        minutes += 1
        seconds = 0
    }else if minutes == 60 {
        hours += 1
        minutes = 0
    }

    timerString = "\(hours):\(minutes):\(seconds)"        
    theTimer.text = timerString      
    defaults.set(theTimer.text, forKey: TimeData.allCurrentTime)
}

// I then created a function which I called in the viewdidload above

func checkForSavedTimer() {
   let allCurrentTime = defaults.value(forKey: TimeData.allCurrentTime) as? String ?? ""
   theTimer.text = allCurrentTime
}

我认为这会将来自 theTimer 的字符串保存到 UserDefaults,然后在 viewDidLoad 中将其取出并保存到“theTimer.text”,但结果是 00:00:00

【问题讨论】:

  • 只需在 viewDidLoad 函数的末尾添加 checkForSavedTimer() 而不是开头

标签: swift xcode4 userdefaults


【解决方案1】:

当您调用checkForSavedTimer() 函数时,它可能会从UserDefaults 获得正确的值,但是您在两行之后将计时器文本设置回00:00:00。如果来自UserDefaults 的值是nil,则需要删除该行并在checkForSavedTimer() 函数中添加一些逻辑以将值设置为00:00:00

override func viewDidLoad() {
    super.viewDidLoad()

    checkForSavedTimer()
    marksSavedData()
    // Remove this -> theTimer.text = "00:00:00"
    theTimer.font = UIFont(name: "Menlo-BoldItalic", size: 40)
    marksTableView.isHidden = false
}

func checkForSavedTimer() {

    // Set the timer text to the value from UserDefaults or "00:00:00" if the value is nil
    theTimer.text = defaults.string(forKey: TimeData.allCurrentTime) ?? "00:00:00"
}

此外,最好使用.string(forKey:)UserDefaults 获取String,因为该值已经为您输入,因此您无需添加as? String

【讨论】:

  • 我太高兴了!!!我昨天在这件事上工作了 7 个小时,却找不到是什么原因造成的,有趣的是得知它是如此简单且如此容易被忽视的事情。
  • @KinneyKare 很高兴我能帮上忙!克服问题是编程时最好的感觉,有时就是这么简单哈哈!
猜你喜欢
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多