我正在尝试在我的应用程序中实现后台刷新。我有一个方法 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/