首页 > 解决方案 > 如何在 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

..不知道该怎么做,因为我尝试了不同的方法,但对我没有任何帮助..希望能得到一些帮助..

标签: swiftxcodecountdown

解决方案


我解决了这个问题。

事实证明,我将 soundEnabled 和 soundDisabled 的原始值传递给 Timer 视图控制器,而没有考虑导致崩溃的 userDefault 中的更新值,因为 soundSwitch.isOn 和vibrationSwitch.isOn 仅存在于设置视图控制器中,因此没有价值(我认为这就是解释)..

我通过解决了

    userDefaults.bool(forKey: "soundEnabled")

    userDefaults.bool(forKey: "vibrationEnabled")

直接到 Timer 视图控制器。现在它正在正确更新。


推荐阅读