![](/img/trans.png)
[英]How to handle Remote push notifications in didreceiveRemoteNotification in AppDelegate
[英]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);
}
獲取當前可見的 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.