Call UserDefaults from extension file

I would like the code that I am writing to have the user be able to call the UserDefaults that sets the background color throughout all UIViewController. So user hits pressButton and throughout all of the view controllers the background color will always be brown. So instead of having to segue variables for settings the settings are automatically updated through a call to the extension file.

                   import UIKit

  class ViewController: UIViewController {
override func viewDidLoad() {

   class twoViewController: UIViewController {
@IBAction func pressButton () {

   extension {

Hi @timswift,
So are you after the code to use UserDefaults or setting the backgroundColor to a set color as saved in UserDefaults?

How about creating an extension function called defaultBackgroundColor that returns the color from UserDefaults or White if this is not set and then set it to the view in every viewDidLoad() function.

However the fun part is that you cannot save UIColor directly to UserDefaults, so you will need to use NSKeyedArchiver and NSKeyedUnarchiver

Try this,

extension UIViewController {
    func defaultBackgroundColor() -> UIColor {
        guard let colorData = (UserDefaults.standard.object(forKey: "DefaultColor") as? Data) else { return UIColor.white }
        return NSKeyedUnarchiver.unarchiveObject(with: colorData) as! UIColor

and in the viewDidLoad, you can call the function defaultBackgroundColor()

oh and yes, if you need to save the color at any point, then you need to use the NSKeyedArchive as

let colorData: Data = NSKeyedArchiver.archivedData(withRootObject:
UserDefaults.standard.set(colorData, forKey: "DefaultColor")

replace with the color you want to save, and you can create an extension on UserDefaults to save color.



This topic was automatically closed after 166 days. New replies are no longer allowed.