I am trying to allow my app to save UIColors in settings, and when I tried to save the settings for the background color it worked. But when I add a second block of code that should allow me to save a second UIColor, it gives me the error - Fatal error: Unexpectedly found nil while unwrapping an Optional value. Can someone show me how to save the second UIColor without an error?
// First UIColor save - Works
var dd = UIColor(hex: UserDefaults.standard.value(forKey: "TheMainUIColour") as! String )
UserDefaults.standard.set(dd.toHexString, forKey: "TheMainUIColour")
let mainBackgroundColour = UserDefaults.standard.value(forKey: "TheMainUIColour") as! String
let color = UIColor(hex: mainBackgroundColour)
self.view.backgroundColor = dd
// Second UIColor Save - Doesnt Work
let dd2: UIColor = UIColor(hex: UserDefaults.standard.value(forKey: "TheMainUIColour2") as! String )
UserDefaults.standard.set(dd2, forKey: "TheMainUIColour2")
let mainBackgroundColour2 = UserDefaults.standard.value(forKey: "TheMainUIColour2") as! String
let color2 = UIColor(hex: mainBackgroundColour2)
The problem is
var dd2:UIColor = UIColor(hex: UserDefaults.standard.value(forKey: "TheMainUIColour2") as! String )
it reads from defaults not save , don't use ! to read from defaults as the stored value may be nil , jsut use if let to check the existence of it in defaults or not , if exists use it , if not save the value you want , wjen you open the app again it will read that stored value
if let saved = UserDefaults.standard.string(forKey: "TheMainUIColour2")
{
var dd = UIColor(hex:saved)
}
else
{
print("No saved color")
let dd = UIColor.red
UserDefaults.standard.set(dd.toHexString, forKey: "TheMainUIColour2")
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments