IOS Swift 处理全局事件

IOS Swift handle global events

我如何处理由通知中心触发的全局事件,例如在我的 API class 如果收到错误响应,我会触发一个事件,例如(500)。当触发该事件时,应在视图控制器处于活动状态时显示 UIAlert,或者在注销时应显示登录视图控制器。

据我所知,没有简单的方法来获取当前视图控制器以便与其交互。 (请注意,我的根视图控制器 不是 导航控制器)。

这种方式获取当前视图控制器是否太难(不使用导航控制器时)?

// on your app delegate    
getCurrentViewController(self.window!.rootViewController!)

func getCurrentViewController(viewController:UIViewController)-> UIViewController{

    if let navigationController = viewController as? UINavigationController{
       return getCurrentViewController(navigationController.visibleViewController)
    }

    if let viewController = viewController?.presentedViewController {

        return getCurrentViewController(viewController)

    }else{

        return viewController
    }
}

广播通知

NSNotificationCenter.defaultCenter().postNotificationName("erro400", object: nil)

接收

override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "ErroOccure", name: "erro400", object: nil)
}

func ErroOccure()
{
    //present alert from here
   // do whatever you want
}

完成后必须删除通知。

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

无论您的视图控制器是否嵌入 UINavigationController 中,都可以使用的替代解决方案是 subclass UIViewController。此 class 将处理接收发生错误的 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 的子class。请确保,如果您覆盖 viewWillAppearviewWillDisappear,您调用 super.viewWillAppearsuper.viewWillDisappear.