extension UIViewController {
func dismissToRoot(animated: Bool = true) {
var initialPresentingViewController = self.presentingViewController
while let previousPresentingViewController = initialPresentingViewController?.presentingViewController {
initialPresentingViewController = previousPresentingViewController
}
if let snapshot = view.snapshotView(afterScreenUpdates: true) {
initialPresentingViewController?.presentedViewController?.view.addSubview(snapshot)
}
initialPresentingViewController?.dismiss(animated: animated)
}
}
class YourViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func backButtonTapped(_ sender: UIButton) {
self.dismissToRoot(animated: true)
}
}