从 navigationStack 中删除 ViewController 并添加它的新实例

Remove a ViewController from navigationStack and add a new instance of it

我有一个嵌入了导航控制器的 SongNamesViewController。从列表中选择歌曲时,我打开 PlaySongViewController 并使用以下函数添加到 navigationController:

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

现在,消息通过远程推送通知到达。用户点击推送通知图标,然后我使用 "openPlaySongViewController()" 函数显示歌曲。如果另一个推送通知到来,然后我在现有 PlaySongViewController 之上显示另一个 PlaySongViewController。

当前流量:(NavigationController)->SongNamesViewController>PlaySongViewController->PlaySongViewController

如何在添加 PlaySongViewController 的新实例之前删除 navigationController 上现有的 PlaySongViewController?

我尝试了以下方法,但 navigationController 上的 PlaySongViewController 没有消失。

for viewController in self.navigationController!.viewControllers {                
     if viewController.isKind(of: PlaySongViewController.self) {                   
          viewController.removeFromParent()                                 
     }
}

topViewController returns 导航堆栈顶部的内容。因此,如果需要,您应该 pop 它。

func removeLastControllerIfNeeded() {
    guard navigationController?.topViewController is PlaySongViewController else { return }
    navigationController?.popViewController(animated: true)
}