1

I have a SongNamesViewController with navigationController embedded. When a song is chosen from a list I open PlaySongViewController and add to the navigationController using following function:

func openPlaySongViewController() {     
  let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
  let playSongViewController = storyBoard.instantiateViewController(withIdentifier: "playSongViewController")
     self.navigationController?.pushViewController(playSongViewController, animated: true)
}

Now, a message arrives via remote push-notification. The user taps on the push-notification icon and then I display the song using "openPlaySongViewController()" function. If another push-notification comes and then I display another PlaySongViewController on top of existing PlaySongViewController.

Current flow: (NavigationController)->SongNamesViewController>PlaySongViewController->PlaySongViewController

How do I remove the existing PlaySongViewController that is on the navigationController before adding a new instance of PlaySongViewController?

I tried the following but the PlaySongViewController that is on navigationController does not go away.

for viewController in self.navigationController!.viewControllers {                
     if viewController.isKind(of: PlaySongViewController.self) {                   
          viewController.removeFromParent()                                 
     }
}
Katlock
  • 1,200
  • 1
  • 17
  • 41
  • Here `(NavigationController)->SongNamesViewController>PlaySongViewController->PlaySongViewController` you have 2 instances of `PlaySongViewController` Do you need to remove the 2 or the last 1 – Shehata Gamal Oct 31 '19 at 22:03
  • I want to remove the existing PlaySongViewController that is on the navigationController before adding another one. – Katlock Oct 31 '19 at 22:33

1 Answers1

1

topViewController returns what is on top of the navigation stack. So you should pop it if needed.

func removeLastControllerIfNeeded() {
    guard navigationController?.topViewController is PlaySongViewController else { return }
    navigationController?.popViewController(animated: true)
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • This does this: PlaySongViewController->SongNamesViewController->PlaySongViewController. Not sure why it doesn't go SongNamesViewController. It's as if the code "self.navigationController?.pushViewController(playSongViewController, animated: true)" doesn't add the viewcontroller. – Katlock Nov 01 '19 at 17:18