Search code examples
iosswiftuitableviewnsuserdefaultsuicolor

Swift - Adding UserDefaults to NotificationCenter


I implemented a NotificationCenter whenever you tap on a specific TableViewCell to perform that notification inside another ViewController, for this example the other ViewController background colour turns pink which works fine, but my question is how do I save the state of the pink colour being the same inside that ViewController using UserDefaults?

To clarify this much better:

  • ViewController #2 contains the TableViewCell that performs the action when pressed

  • ViewController #1 is the view where the colour changes to Pink.

What I want to achieve?

Save the state of the pink colour in ViewController #1 using UserDefaults

ViewController #1 Code

- viewDidLoad

override func viewDidLoad()
{
    NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);
}

- TestNotification Function

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

    print("This is a message to say it is working")
}

ViewController #2 Code

didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if indexPath.row == 0
    {

        if traitCollection.userInterfaceStyle == .light
        {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil, userInfo: nil)
            self.dismiss(animated: true, completion: nil)
        }
        else if traitCollection.userInterfaceStyle == .dark
        {
            ...
        }
    }
}

Solution

  • You can set color in UserDefaults when you notification method called. So, updated your code as follow in ViewController1:

    @objc func testNotifcation(notification: NSNotification) { 
    
        table.backgroundColor = UIColor.systemPink
    
        let colorData = NSKeyedArchiver.archivedData(withRootObject: UIColor.systemPink)
        UserDefaults.standard.set(colorData, forKey: "savedColor")
        UserDefaults.standard.synchronize()
    
        print("This is a message to say it is working")
    }
    

    Then, In view did load, you need to add code to fetch saved color and set it as background. So update code in viewDidLoad in ViewController1.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);
    
        if let colorData = UserDefaults.standard.value(forKey: "savedColor") as? Data,
            let savedColor = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
        {
            table.backgroundColor = savedColor
        }
    }
    

    I hope this will help you.