Josh Schlabach Josh Schlabach - 3 months ago 18
Swift Question

How do I save a UIColor with NSUserDefaults?

I'm trying to program my code so that if the user presses the Night Button the background will turn black and stay black if the user closes the app. (Same goes for day mode.)

Please note: I already coded buttons and when they press it, all of the scenes change to that mode.

Here's my code where I'm going going to need the background color to be saved: (I need it in both if statements)

if GlobalData.dayBool == true && GlobalData.night == false {
backgroundColor = GlobalData.dayColor
}

if GlobalData.nightBool == true && GlobalData.dayBool == false {
backgroundColor = GlobalData.nightColor
}


My Night and Day Colors:

struct GlobalData {
static var score = 0
static var dayColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0)
static var nightColor = UIColor(red:0.10, green:0.10, blue:0.10, alpha:1.0)
static var dayBool = true
static var nightBool = true
}

Answer
extension NSUserDefaults {
    func setColor(value: UIColor?, forKey: String) {
        guard let value = value else {
            setObject(nil, forKey:  forKey)
            return
        }
        setObject(NSKeyedArchiver.archivedDataWithRootObject(value), forKey: forKey)
    }
    func colorForKey(key:String) -> UIColor? {
        guard let data = dataForKey(key), color = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? UIColor
        else { return nil }
        return color
    }
}

You can also create a UIColor with a getter setter to save it automatically as follow:

var nightColor: UIColor? {
    get {
        return NSUserDefaults().colorForKey("nightColor")
    }
    set {
        NSUserDefaults().setColor(newValue, forKey: "nightColor")
    }
}