[英]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?现在,如果每个视图代表一个 swift 文件,那么我是否需要在每个 swift 文件中实现相同的代码来处理传入的推送通知,或者我猜测有更好的设计或技术来解决这个问题?
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获取当前可见的 Top ViewController 的 Helper 方法
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.