取消presentingviewController后显示警报

时间:2019-04-18 08:04:26

标签: ios swift in-app-purchase uialertcontroller

用户购买completion handler时通知我并关闭viewController。但是,我想在alert被解散后向用户显示/显示viewController。在我进入调试器的那一刻,它遍历了代码,但未显示警告。仍然内置在苹果中,上面写着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")
        })
    }
}

1 个答案:

答案 0 :(得分:2)

您需要致电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)
        })
    }
}