在AppDelegate.m的屏幕上获取当前显示的UIViewController [英] Get the current displaying UIViewController on the screen in AppDelegate.m
问题描述
屏幕上的当前 UIViewController
需要通过设置徽章视图来响应来自APN的推送通知。但是如何在方法应用程序中获取
: UIViewController
:didReceiveRemoteNotification AppDelegate.m
?
The current UIViewController
on the screen need to response to push-notifications from APNs, by setting some badge views. But how could I get the UIViewController
in methodapplication:didReceiveRemoteNotification
: of AppDelegate.m
?
我尝试使用 self.window.rootViewController
来获取当前显示 UIViewController
,它可能是 UINavigationViewController
或其他类型的视图控制器。我发现 UINavigationViewController
的 visibleViewController
属性可用于获取 UIViewController
在屏幕上。但如果它不是 UINavigationViewController
,我该怎么办?
I tried use self.window.rootViewController
to get the current displaying UIViewController
, it may be a UINavigationViewController
or some other kind of view controller. And I find out that the visibleViewController
property of UINavigationViewController
can be used to get the UIViewController
on the screen. But what could I do if it is not a UINavigationViewController
?
任何帮助表示赞赏!相关代码如下。
Any help is appreciated! The related code is as following.
AppDelegate.m
...
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//I would like to find out which view controller is on the screen here.
UIViewController *vc = [(UINavigationViewController *)self.window.rootViewController visibleViewController];
[vc performSelector:@selector(handleThePushNotification:) withObject:userInfo];
}
...
ViewControllerA.m
- (void)handleThePushNotification:(NSDictionary *)userInfo{
//set some badge view here
}
推荐答案
当你的控制器不是 UINavigationController
时,你也可以使用 rootViewController
:
You can use the rootViewController
also when your controller is not a UINavigationController
:
UIViewController *vc = self.window.rootViewController;
一旦你知道了根视图控制器,那么它取决于你如何构建你的UI,但是你可能会找到一种方法来浏览控制器层次结构。
Once you know the root view controller, then it depends on how you have built your UI, but you can possibly find out a way to navigate through the controllers hierarchy.
如果你提供一些关于你定义你的应用程序的方式的更多细节,那么我可能会给出更多提示。
If you give some more details about the way you defined your app, then I might give some more hint.
编辑:
如果你想要最顶层的视图(不是视图控制器) ,你可以检查
If you want the topmost view (not view controller), you could check
[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];
虽然这个视图可能看不见甚至被其某些子视图覆盖......
although this view might be invisible or even covered by some of its subviews...
再次,这取决于你的用户界面,但这可能会有所帮助......
again, it depends on your UI, but this might help...
这篇关于在AppDelegate.m的屏幕上获取当前显示的UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!