我如何处理由通知中心触发的全局事件,例如在我的 API 类中,如果收到错误响应,我会触发一个事件,例如(500)。当该事件被触发时, UIAlert 应该显示在任何事件的 View Controller 上,或者在注销时应该显示登录 View Controller 。
据我所知,没有简单的方法来获取当前 View Controller 以便与其交互。 (请注意,我的 Root View Controller 不是导航 Controller )。
最佳答案
另一种解决方案是子类化 UIViewController
,无论您的 View Controller 是否嵌入 UINavigationController
中,它都可以工作。此类将处理接收发生错误的 NSNotification 并处理显示警报:
class MyViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "errorOccured",
name: "ErrorNotification",
object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "ErrorNotification", object: nil)
}
func errorOccured() {
// Present an UIAlertViewController or the login screen.
}
}
现在,任何在发布错误通知时应显示警报的 UIViewController
都必须是 MyViewController
的子类。只要确保在重写 viewWillAppear
或 viewWillDisappear
时调用 super.viewWillAppear
或 super.viewWillDisappear
即可。
关于IOS Swift 处理全局事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30618361/