Search code examples
iosswiftuikit

Call a function only once in UIViewController when a UIButton is clicked


I.have been reading some questions as to how to achieve this behavior and I have seen examples of calling a function work only once by calling it inside viewDidLoad section, but what I am trying to do is to call a function called savedFunc inside a @obj click event the first time this UIViewController is presented because then the user will be redirected to another view that I called SavedCanvasViewController()

   @objc func returnToView(_ sender: UIButton) {
        let vsdd = SavedCanvasViewController()

        // if is the first time user is in this view call this function below
        savedFunc()
     
        vsdd.modalPresentationStyle = .fullScreen
        vsdd.modalTransitionStyle = .coverVertical
        present(vsdd, animated: true)
    }

Since I am going to be coming back and forward to the view controller where the returnToView is executed, I only want to make use of my savedFunc function once and ignore it whenever a user is back to this view. Is it possible to make it work like that?


Solution

  • If you put returnToView into your viewDidLoad it will not be executed because at the time viewDidLoad gets called, the view controller itself has not fully setup yet and it's not visible on the window hierarchy. So you cannot use present. You may think to put it in viewWillAppear or viewDidAppear. However, it has a drawback: whenever you back from another present or back from navigationController.pushViewController, it will get called again.

    So, I think this will achieve your goal. It works on a single instance of ViewController.

    class ViewController: UIViewController {
        private var isExecuteSaveFunc = false
        
        @objc func returnToView(_ sender: UIButton) {
            let vsdd = SavedCanvasViewController()
    
            if !isExecuteSaveFunc {
                savedFunc()
                isExecuteSaveFunc = true
            }
         
            vsdd.modalPresentationStyle = .fullScreen
            vsdd.modalTransitionStyle = .coverVertical
            present(vsdd, animated: true)
        } 
    }
    

    In case you want savedFunc to execute once during the lifetime of the app, I think UserDefaults will fit.