Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine that UIViewController was started for the first time?

Tags:

ios

swift

I have a ViewControllers hierarchy, with UINavigationViewController as the root.
How can I find out whether some ViewController was started for the first time or it was started as a result of unwinding of the navigation stack?

like image 321
spin_eight Avatar asked Sep 13 '16 18:09

spin_eight


1 Answers

Assuming you wish to know if viewWillAppear: (or viewDidAppear:) is being called when the view controller is first being displayed or if it's being displayed because another view controller has been dismissed, you can easily do the following:

Newer Swift versions:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if isBeingPresented || isMovingToParent {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}

Older Swift versions:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    if isBeingPresented() || isMovingToParentViewController() {
        // This is the first time this instance of the view controller will appear
    } else {
        // This controller is appearing because another was just dismissed
    }
}
like image 110
rmaddy Avatar answered Nov 07 '22 00:11

rmaddy