swiftstringuicoloruserdefaultsnskeyedunarchiver

Save/Get UIColor from UserDefaults


I need some help to load and read UIColor from UserDefaults.

I found a nice extension to do that:

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)
 }

}

But NSKeyedUnarchiver.unarchiveObject was deprecated recently, so i don't know how to get data from it.

Any suggestions? Thank you!


Solution

  • In your code, simply replace 2 lines, i.e

    Replace

    color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor

    with

    color = try! NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)

    //// Here you can use try? instead of try! and wrap it in if-let statement. Your choice.

    and

    Replace

    colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?

    with

    colorData = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)

    Also, use Data instead of NSData in var colorData: NSData? ,i.e.

    var colorData: Data?