Search code examples
iosswiftuserdefaults

How to count how many times all classes are called


I want the user to be able to know how many times they have visited each class. Then add together the totals from each page together to form a group sum. I want to print the total sum in the log file in each of the two view controllers. So just one string should be printed.

class oneV: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.set(true, forKey: "VC1")
    }
}

class twoV: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.set(true, forKey: "VC2")
    }
}

Solution

  • If you mean visited each view controller, when you say visited each class. Then i'd recommend you do it viewDidAppear.

    class YourViewController: UIViewController {
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            let key = String(describing: type(of: self))
            let count = UserDefaults.standard.value(forKey: key) as? Int ?? 0
            UserDefaults.standard.set(value + 1, forKey: key)
        }
    
    }
    

    To make it simpler, you could use an extension on UIViewController.

    extension UIViewController {
    
        func updateVisitCount() {
            let key = String(describing: type(of: self))
            let count = UserDefaults.standard.value(forKey: key) as? Int ?? 0
            UserDefaults.standard.set(count + 1, forKey: key)
        }
    
    }
    

    Or, if you need this for every view controller that you create, then you can create a base view controller which you would use everywhere instead of UIViewController.

    class BaseViewController: UIViewController {
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            updateVisitCount()
        }
    
    }