我目前正在开发一个应用程序,该应用程序在后台运行超过五分钟后需要返回另一个视图。为了做到这一点,我必须在按下主页按钮后在后台运行一个计时器,或者在短信或电话等中断的情况下,然后,五分钟后,应用程序将需要转到另一个视图。我知道必须使用 applicationDidBecomeActive 方法,但是如何使用呢?我也知道可以在 applicationDidBecomeActive 中刷新视图,但这是如何完成的?(我没有使用故事板。)
2 回答
实际上,您应该使用 的applicationDidEnterBackground
applicationWillEnterForeground
委托方法UIAppDelegate
或通过注册到适当的系统通知来执行此操作(didBecomeActive
在其他情况下也会调用,例如当 aUIAlertView
从屏幕上解除时)。
这应该是(可能包括语法问题,我在这里是文本框编码):
在
viewDidLoad
视图控制器的方法中,注册到通知:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
实现
willEnterForeground:
和didEnterBackground:
方法。在样本中使用或willEnterForeground:
的当前时间。再次采样时间并计算时间差。由于此方法是在视图控制器内部实现的,因此您可以根据需要操作您的子视图。CACurrentMediaTime()
[NSDate date]
didEnterBackground:
self.view
不要忘记删除您
dealloc
方法上的观察者(viewDidUnload
自 iOS 6.0 起已弃用,因此请注意):[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil] [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]
这是你如何做到的。我刚刚制作了一个测试应用程序,我确认它运行良好。代码:
#import "AppDelegate.h"
#import "ViewController.h"
#import "theView.h"
NSTimer *theTimer;
UIViewController *theViewController;
BOOL theTimerFired = NO;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Set a 5 minute timer (300 seconds)
theTimer = [NSTimer scheduledTimerWithTimeInterval:300.0 target:self selector:@selector(presentVC) userInfo:nil repeats:NO];
}
- (void)presentVC
{
// Set a boolean to indicate the timer did fire
theTimerFired = YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Check to see if the timer did fire using the previous boolean we created
if (theTimerFired == YES)
{
theViewController = [[UIViewController alloc]initWithNibName:@"theView" bundle:nil];
[self.viewController presentViewController:theViewController animated:YES completion:NULL];
[theTimer invalidate];
}
}
@end