sk123
sk123

Reputation: 600

Show alert after dismissing presentingviewController

When a user purchased completion handler notify me and dismiss viewController. However, I want to display/show an alert to the user after viewController dismissed. At the moment when I step through in the debugger, it goes through the code but the alert isn't being shown. Still getting inbuilt in apple one that says All set. Is there a way I can display my alert after dismissing the viewController.

override func viewWillDisappear(_ pAnimated: Bool) {
    super.viewWillDisappear(pAnimated)
    self.notifyForUserHasPurchasedProduct {
        self.presentingViewController?.dismiss(animated: true, completion: {
            UIAlertController.bs_showAlertFrom(self, title: "AppName", message: "Thank you. Your purchase was successful")
        })
    }
}

Upvotes: 1

Views: 857

Answers (1)

Agisight
Agisight

Reputation: 1818

You need to call self.present(alert, animated: true) to show alert. When ViewController self is not present, you need to change code to presentedViewController.present(alert, animated: true)

I have builded some functions:

extension UIViewController {

    func topMostViewController() -> UIViewController {

        if let presented = self.presentedViewController {
            return presented.topMostViewController()
        }

        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController() ?? navigation
        }

        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController() ?? tab
        }

        return self
    }
}

func getRootController () -> UIViewController { // function in global scope
    return (UIApplication.shared.delegate?.window!!.rootViewController)!
}

And then use them like here:

override func viewWillDisappear(_ pAnimated: Bool) {
    super.viewWillDisappear(pAnimated)
    self.notifyForUserHasPurchasedProduct {
        self.presentingViewController?.dismiss(animated: true, completion: {
        let alert = UIAlertController(title: "AppName", message: "Thank you. Your purchase was successful", preferredStyle: .alert)

        let topC = getRootController().topMostViewController()
        topC.present(alert, animated: true, completion: nil)
        })
    }
}

Upvotes: 2

Related Questions