如何正确处理接收远程推送通知

How to handle receiving remote push notifications properly

我有一个关于如何处理传入推送通知的问题。如您所知,一个应用程序可以有很多视图。例如,当我收到通知时,我想在用户所在的视图中显示警报或做其他事情(因为我真的不知道用户在收到通知时将在哪个视图中)。现在,如果每个视图代表一个 swift 文件,那么我是否需要在每个 swift 文件中实现相同的代码来处理传入的推送通知,或者我猜想有更好的设计或技术来处理这个?

我已经搜索了一段时间,我所能找到的只是人们在应用程序处于后台而不是前台时遇到问题:/

任何东西都很好,教程、指南、代码示例。如果可能的话,有很多方法可以解决这个问题,这样我就可以研究它们并选择最适合我的方法。

希望这会有所帮助:

收到通知时查找可见视图控制器。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    let currentViewControlelr :UIViewController = topViewController(UIApplication.sharedApplication().keyWindow?.rootViewController)!;

    if(currentViewControlelr == YourViewController()){

        //Display Alert 
        let alert = UIAlertView()
        alert.title = "Alert"
        alert.message = "Here's a message"
        alert.addButtonWithTitle("Understod")
        alert.show()

        //Implement other function according to your needs
    }

    NSLog("UserInfo : %@",userInfo);
    }

获取顶部ViewController的辅助方法

func topViewController(base: UIViewController? ) -> UIViewController? {
    if let nav = base as? UINavigationController {
        return topViewController(nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
        if let selected = tab.selectedViewController {
            return topViewController(selected)
        }
    }
    if let presented = base?.presentedViewController {
        return topViewController(presented)

    }
    return base
    }