SRMR
SRMR

Reputation: 3134

Refresh View and Data everytime app opens

I have a TableView that needs to be refreshed every time the app opens, but I can't get it to do that.

The reason for this, is that there is new data for every day stored in a JSON file, so the app needs to refresh to find out if its a new day so it can load the new data.

I tried moving my code from viewDidLoad to viewWillAppear thinking that would do the trick, but it didn't.

Any ideas?

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...
}

Upvotes: 0

Views: 261

Answers (1)

nburk
nburk

Reputation: 22731

I had a similar issue recently, my misunderstanding was that viewWillAppear / viewDidAppear would be called whenever the app opens (and the corresponding view controller is shown). That is in fact no the case!

How you do this is by adding an observer for a NSNotification like so:

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

iOS sends a system NSNotification when your app is launched. The name of the notification is held in the constant UIApplicationDidBecomeActiveNotification. You can add your UITableViewController that holds the data (or any other class for that matter) as an observer for that notification and perform the update whenever the notification is received.

Upvotes: 3

Related Questions