每次打开应用程序时刷新视图和数据

Refresh View and Data everytime app opens

我有一个 TableView 需要在每次应用程序打开时 刷新 ,但我无法做到这一点。

这是因为 每天 的新数据存储在 JSON 文件中,因此应用程序需要刷新以了解其是否新的一天,以便它可以加载新数据。

我尝试将我的代码从 viewDidLoad 移动到 viewWillAppear,认为这样可以解决问题,但没有成功。

有什么想法吗?

ViewController.m

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Get current date, remove year from current date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    NSString *dateToday = [formatter stringFromDate:[NSDate date]];
    NSString *dateTodayShort = [dateToday substringToIndex:[dateToday length] -6];

    // Get JSON file path
    NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:@"Days" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
    NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
    days = JSONDictionary[@"days"];

    // Iterate thru JSON to find Data for Today
    NSObject *todayJson;
    for (NSObject *object in days) {
        NSString *dateObject = [object valueForKey:@"day"];
        if ([dateObject isEqualToString:dateTodayShort]) {
            todayJson = object;
            NSString *textToday = [todayJson valueForKey:@"text"];
            NSString *backgroundImageToday = [todayJson valueForKey:@"backgroundImage"];
            textGlobal = textToday;
            backgroundImageGlobal = backgroundImageToday;
        }
    }
    // Other set up code...
}

我最近遇到了类似的问题,我的误解是 viewWillAppear / viewDidAppear 会在应用程序打开时调用(并显示相应的视图控制器)。事实并非如此!

如何做到这一点是通过为 NSNotification 添加一个 observer,如下所示:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:UIApplicationDidBecomeActiveNotification object:nil];

iOS 在您的应用启动时发送系统 NSNotification。通知的名称保存在常量 UIApplicationDidBecomeActiveNotification 中。您可以添加保存数据的 UITableViewController(或与此相关的任何其他 class)作为该通知的观察者,并在收到通知时执行更新。