在 AppDelegate.m 中获取当前显示在屏幕上的 UIViewController [英] Get the current displaying UIViewController on the screen in AppDelegate.m
问题描述
屏幕上当前的 UIViewController
需要通过设置一些徽章视图来响应来自 APNs 的推送通知.但是如何在 AppDelegate.m
的方法application:didReceiveRemoteNotification
: 中获取UIViewController
?
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.
如果你想要最顶层的view(不是视图控制器),你可以检查
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屋!