在applicationDidBecomeActive之后切换视图

时间:2013-07-20 17:46:39

标签: ios

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

2 个答案:

答案 0 :(得分:1)

实际上,您应该使用applicationDidEnterBackground的{​​{1}} applicationWillEnterForeground委托方法执行此操作,或者注册相应的系统通知(UIAppDelegate也会在其他场合调用,例如当didBecomeActive从屏幕上被解雇时。)

这应该是一些内容(可能包括语法问题,我在这里是文本框编码):

  • 在视图控制器的UIAlertView方法中,注册通知:

    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方法上的观察者(自iOS 6.0以来已弃用dealloc,所以要小心):

    viewDidUnload

答案 1 :(得分: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