Search code examples
iosswiftuiviewcontroller

How to call function only once in UIViewController?


I have function call (pop view) in my 1st view controller which have to be called only once in app. Since then whenever I return back to 1st View controller the function need not to be called again.

func popView() {
        let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popView") as! popView
        self.addChild(popOverVC)
        popOverVC.view.frame = self.view.frame
        self.view.addSubview(popOverVC.view)
        popOverVC.didMove(toParent: self)
    }

I have tried the following code and previous other sources in stack overflow, didn't work though..

 ///// Once Action in View Controller
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        if self.isBeingPresented || self.isMovingToParent {
         // Perform an action that will only be done once
             popView()
        }
    }

Solution

  • If you want to call that PopView function only once in your App then try this,

     override func viewDidLoad() {
         super.viewDidLoad()
         showPopUp()
     }
    
    func showPopUp() {
            let showPop: Bool = UserDefaults.standard.bool(forKey: "showPop")
            if showPop == false {
                // don't show ----Pop
            } else {
               openPop()
               UserDefaults.standard.set(false, forKey: "showPop")
            }
            
     }
    

    This will call the pop up only once in app life cycle...