ios - 如何在后台刷新期间从 AppDelegate.m 访问 View Controller

标签 ios uinavigationcontroller

我正在尝试在我的应用程序中实现后台刷新。我有一个方法 refreshMessages 位于我的一个 UIViewControllers 中(我正在使用 UINavigationController)。我需要从 AppDelegate.m 访问这个 Controller 。

通常我会做这样的事情:

UINavigationController *navigationController = [self.window.rootViewController navigationController];

获取导航 Controller ,然后我可以从那里访问它们。但现在肯定行不通了。该应用程序在后台,没有窗口显示。关于如何解决这个问题的任何想法?谢谢!

这是我的后台刷新:

-(void)application:(UIApplication *)application
performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {



    NSLog(@"Doing the background refresh");

    UINavigationController *navigationController = [self.window.rootViewController navigationController];
    NSLog(@"Number of controllers is %d", [[navigationController viewControllers] count]);
    //There are zero controllers?!!! Must be because no window is showing
    completionHandler(UIBackgroundFetchResultNewData);



}

最佳答案

是的,你是对的。 window 将为 nil,因为它将不再位于 View 层次结构中。

一个厚颜无耻的解决方案是通过在其中创建一个属性来将 View Controller 的引用保存在 AppDelegate 中。您可以在应用程序进入后台时通过订阅 View Controller 中的相关通知来分配它。

编辑:添加代码

在您的AppDelegate.h

@property (nonatomic, weak) YourViewController *yourViewController;

在 YourViewController.m 中,在 viewDidLoad 的某处

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];

appWillResignActive 的实现

-(void)appWillResignActive:(id)sender {
    YourAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    delegate.yourViewController = self;
}

在您的完成处理程序中

[self.yourViewController refreshMessages]

此外,请确保在 View Controller 被释放后移除观察者。

关于ios - 如何在后台刷新期间从 AppDelegate.m 访问 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755075/

相关文章:

android - Unity 初学者 - 点击/点击多次触发

ios - 在核心图散点图中加入缺失点

iphone - 使用 popToRootViewController 时,我丢失了导航栏

ios - UINavigationController 不会在后退按钮上弹出 View

ios - 以编程方式设置导航栏按钮

ios - Facebook API 分页不起作用

iphone - 使用类型为 'NSMutableArray *__strong' 的表达式初始化 'SecondViewController *' 的不兼容指针类型

ios - 扫描 PDF 时未检测到空格 - iOS (CGPDFScanner)

iOS 11 后退按钮问题

ios - 过渡到导航 View Controller