来自背景时刷新应用程序

时间:2014-08-14 01:22:38

标签: ios objective-c appdelegate

在我的应用程序中我有一个mainViewController从服务器获取信息。 我想保持mainViewController最新,所以当用户来自后台我需要更新数据。

我试过这段代码

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:[NSDate date] forKey:@"exitTime"];

    [defaults synchronize];

}




- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSDate *exitTime = [defaults objectForKey:@"exitTime"];

    NSDate *currentTime = [NSDate date];

    //This will return the number of seconds elapsed:

    NSTimeInterval diff = [currentTime timeIntervalSinceDate:exitTime];

    NSLog(@"time gap %f", diff);


    if (diff > 300.0f){

    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUINotification" object: nil];


    }

这是我在每个ViewControllers中添加的内容:

//in viewDidLoad:
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(update:) name: @"UpdateUINotification" object: nil];
    Finally, declare the update: method that will be called when the notification is triggered.



-(void)update{
    mainViewController *main = [self.storyboard instantiateViewControllerWithIdentifier:@"mainController"];
    [self.navigationController pushViewController:main animated:YES];
}

该代码运行良好,但我的应用程序中有20多个ViewControllers,所以我的问题是,有任何方法可以重新加载应用程序(因为mainViewController是我的初始视图)或者是为所有viewControllers本地做的应用程序?

0 个答案:

没有答案