1

我目前正在开发一个应用程序,该应用程序在后台运行超过五分钟后需要返回另一个视图。为了做到这一点,我必须在按下主页按钮后在后台运行一个计时器,或者在短信或电话等中断的情况下,然后,五分钟后,应用程序将需要转到另一个视图。我知道必须使用 applicationDidBecomeActive 方法,但是如何使用呢?我也知道可以在 applicationDidBecomeActive 中刷新视图,但这是如何完成的?(我没有使用故事板。)

4

2 回答 2

1

实际上,您应该使用 的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]

于 2013-07-20T18:22:20.587 回答
0

这是你如何做到的。我刚刚制作了一个测试应用程序,我确认它运行良好。代码:

#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
于 2013-07-20T18:19:41.873 回答