Search code examples
iosviewdidloadviewdidappear

iOS: Refresh Data When App is Brought to Foreground


I'm getting data off the server via JSON and displaying it on Labels. I've added that method in viewDidLoad.

I want to refresh the data when the user opens the app again. Currently, even if I kill the app in the simulator and start the app again, it doesn't refresh.

I tried the viewDidAppear method, but it isn't being executed for some reason.

-(void)viewDidAppear{
        NSLog(@"Called viewDidAppear");
}

This is never called. I tried to minimize the app but it didn't work.


Solution

  • I followed this tutorial - http://leejon.es/notifying-a-viewcontroller-with-uiapplicationdidbecomeactivenotification/

    First, attach to the notification in the viewWillAppear method of the target view controller:

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        [[NSNotificationCenter defaultCenter] addObserver: self
                                                 selector: @selector( appActivated: )
                                                     name: UIApplicationDidBecomeActiveNotification
                                                   object: nil];
    
    }
    
    
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        [[NSNotificationCenter defaultCenter] removeObserver:self ];
    }
    
    
    - (void)appActivated:(NSNotification *)note
    {
        [self update];
    }