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

时间:2015-12-23 10:54:07

标签: ios swift push-notification push

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

我一直在寻找一段时间,我所能找到的是人们在应用程序处于后台而不是前景时遇到问题:/

一切都会很好,教程,指南,代码示例。如果可能的话,有很多方法可以解决这个问题,所以我可以研究它们并选择最适合我的方式。

1 个答案:

答案 0 :(得分:2)

希望这会有所帮助:

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

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

Helper方法获取当前可见的Top 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
    }