swift - 如何在 userDefaults 中保存用户设置 - Swift
问题描述
我正在开发 CountDown Timer 应用程序,如果时间到了,我会设置计时器以设置闹钟。我做了一个设置 VC 来保存用户是否想要启用声音和振动。我正在尝试使用此代码将用户的首选项保存到 userDefaults
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var soundLabel: UILabel!
@IBOutlet weak var vibrationLabel: UILabel!
@IBOutlet weak var soundSwitch: UISwitch!
@IBOutlet weak var vibrationSwitch: UISwitch!
var soundEnabled = true
var vibrationEnabled = true
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
soundLabel.text = "Sound Enabled"
soundLabel.textColor = .white
vibrationLabel.text = "Vibration Enabled"
vibrationLabel.textColor = .white
soundSavedSettings()
vibrationSavedSettings()
}
@IBAction func soundSwitchPressed(_ sender: UISwitch) {
if soundEnabled {
soundEnabled = false
soundLabel.text = "Sound Disabled"
} else {
soundEnabled = true
soundLabel.text = "Sound Enabled"
}
userDefaults.set(soundEnabled, forKey: "soundEnabled")
}
@IBAction func vibrationSwtichPressed(_ sender: UISwitch) {
if vibrationEnabled {
vibrationEnabled = false
vibrationLabel.text = "Vibration Disabled"
print("\(vibrationEnabled.description)")
} else {
vibrationEnabled = true
vibrationLabel.text = "Vibration Enabled"
print("\(vibrationEnabled.description)")
}
userDefaults.set(vibrationEnabled, forKey: "vibrationEnabled")
}
func soundSavedSettings() {
soundEnabled = userDefaults.bool(forKey: "soundEnabled")
soundSwitch.isOn = soundEnabled
if soundSwitch.isOn {
soundLabel.text = "Sound Enabled"
} else {
soundLabel.text = "Sound Disabled"
}
}
func vibrationSavedSettings() {
vibrationEnabled = userDefaults.bool(forKey: "vibrationEnabled")
vibrationSwitch.isOn = vibrationEnabled
if vibrationSwitch.isOn {
vibrationLabel.text = "Vibration Enabled"
} else {
vibrationLabel.text = "Vibration Disabled"
}
}
}
但是当我运行应用程序并使用开关将声音或振动设置设置为 false 时,当倒数计时器达到 0 时,应用程序崩溃并给我这个错误:
致命错误:在隐式展开可选值时意外发现 nil
对于 soundSwitch.isOn
..不知道该怎么做,因为我尝试了不同的方法,但对我没有任何帮助..希望能得到一些帮助..
解决方案
我解决了这个问题。
事实证明,我将 soundEnabled 和 soundDisabled 的原始值传递给 Timer 视图控制器,而没有考虑导致崩溃的 userDefault 中的更新值,因为 soundSwitch.isOn 和vibrationSwitch.isOn 仅存在于设置视图控制器中,因此没有价值(我认为这就是解释)..
我通过解决了
userDefaults.bool(forKey: "soundEnabled")
和
userDefaults.bool(forKey: "vibrationEnabled")
直接到 Timer 视图控制器。现在它正在正确更新。
推荐阅读
- python - 常规和命名空间包的 sys.path 的导入顺序
- python - 我得到了 python BeautifulSoup 的结果集,但我不知道如何获取其中的 NavigableString
- python - Tkinter,如何使散点图弹出到新窗口
- gatsby - 如何在 gatsby 网站上下载外部文件?
- html - 从容器中分离滚动
- python - 如何使用 model.py 或任何替代选项将打印数据(即终端的 odr_id)添加到数据库?
- sql - 我如何选择每对不同的两列的第一条记录
- python - 乌龟动画在python中是如此之快
- sql - 递归 SQL 查询如何终止以及如何评估它们?
- javascript - 具有多个匹配条件的对象数组与过滤器不匹配