Search code examples
iossegueswift4nsuserdefaultsvar

use userdefults to save user choice but not override segue (swift4)


I need my code below to save whatever is in the var color when it is segued to. When the app starts the color is black and it should be either brown or red expect if it is the first time the user is running the app. The problem is once the user in another view controller chooses a color and segues it to class Jus it should save the color chosen. So the code needs to save whatever color it was segue, so when the user exits the application whatever was segue to it but not interfere with a change of color segue.

    class Jus: UIViewController {
    @IBOutlet weak var text: UILabel!
    var color = ""
    let userDefaults = UserDefaults.standard
    override func viewDidLoad() {

        super.viewDidLoad()
        if color == "a" {
            text.textColor = UIColor.brown

        }
        if color == "b" {
            text.textColor = UIColor.red

        }

    }
}

Solution

  • You can save the color directly with extension according to this thread

    let defaults = UserDefaults.standard
    

    //

    extension UserDefaults {
    
        func colorForKey(key: String) -> UIColor? {
            var color: UIColor?
            if let colorData = data(forKey: key) {
            color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
            }
            return color
        }
    
        func setColor(color: UIColor?, forKey key: String) {
            var colorData: NSData?
            if let color = color {
            colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
            }
            set(colorData, forKey: key)
        }
    
    }
    

    //

    Save

    defaults.setColor(color: UIColor.red, forKey: "myColor") // set
    

    Read

    if let myColor = defaults.colorForKey(key: "myColor")  {
          // set stored color
    }
    else {
           // set default color 
    }