关闭 presentingviewController 后显示警报

Show alert after dismissing presentingviewController

当用户购买时 completion handler 通知我并关闭 viewController。但是,我想在 viewController 被解雇后 display/show 给用户一个 alert 。当我在调试器中单步执行时,它会检查代码,但不会显示警报。仍然内置在苹果中,上面写着 All set。有没有一种方法可以在关闭 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")
        })
    }
}

您需要调用 self.present(alert, animated: true) 来显示警报。当 ViewController self 不存在时,您需要将代码更改为 presentedViewController.present(alert, animated: true)

我构建了一些函数:

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)!
}

然后像这里一样使用它们:

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)
        })
    }
}