Reputation: 55
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.
Upvotes: 2
Views: 902
Reputation: 14504
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
}
Upvotes: 2