简体   繁体   中英

How to handle receiving remote push notifications properly

I have a question regarding how to handle incoming push notifications. As you would know an app can have lots of views. When receiving i would like to for example show an alert or do something else on the view that the user is in(cause i cant really know which view the user will be in when receiving the notification). Now if each view represents a swift file, then would i need to implement the same code in each swift file to handle the incoming push notifications or as i would guess there is a better design or technique to approach this?

I have been searching for a while now and all i could find was people having problems when app was in background not foreground :/

Anything would be nice, tutorial, guide , code examples. And if possible many ways to solve this so i can research them and pick whatever suits me the best.

Hope this will help :

Find visible view controller when receive Notification.

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 Method to get Top ViewController which is visible at the moment

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM