67

I want to reload data in UIViewController when application become active or become foreground.

I know applicationDidBecomeActive is called in AppDelegate class.
But I have to have a global variable for the UIViewController to reload its data in AppDelegate class like this code:

in AppDelegate.m

// global variable
UIViewController *viewController1;
UIViewController *viewController2;

-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [viewController1 reloadData];
    [viewController2 reloadData];
}

But it is inconvenient especially when I have a lot of UIViewControllers.

Can I use applicationDidBecomeActive in UIViewController instead of in AppDelegate class?
Or are there better ways than having global variable for UIViewController?

I also need to use the following method from UIViewControllers:

-(void)applicationWillResignActive:(UIApplication *)application
-(void)applicationDidEnterBackground:(UIApplication *)application
-(void)applicationWillEnterForeground:(UIApplication *)application
1
  • this code doesn't work because [viewController1 reloadData] is executed when viewController1 is not displayed.
    – js_
    Aug 19, 2012 at 11:56

7 Answers 7

149

At the time of reactivation, if you want to carry a particular thing for a view controller, you should register a notification in its viewDidLoad method.

UIApplicationDidBecomeActiveNotification will automatically notify your application and given controller, if they registered for it.

 [[NSNotificationCenter defaultCenter]addObserver:self
                                         selector:@selector(yourMethod)
                                             name:UIApplicationDidBecomeActiveNotification
                                           object:nil];
4
  • Thanks for your answer. Don't I have to resister observer in viewWillApper and remove the observer in viewWillDissapear? Because if I don't remove it in viewWillDisappear, callback method is executed after the view is disappeared and this might cause crash.
    – js_
    Aug 19, 2012 at 12:02
  • 3
    Yes..you should do it in that way only.. If you add the observer in viewDidLoad method, you should remove it in dealloc method. If you add it viewWillAppear, you should remove it in viewWillDisAppear method.
    – Apurv
    Aug 24, 2012 at 1:57
  • dealloc is not necessary on ARC (iOS 7).
    – Felix
    Feb 7, 2014 at 15:14
  • 3
    You can safely write dealloc function while working with ARC. You can deallocate references which are created by malloc, new. You can remove observers in dealloc while working with ARC.
    – Apurv
    Feb 11, 2014 at 13:12
58

Here is an example of registering a notification handler in Swift (adapted from Apurv's answer above):

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(applicationDidBecomeActive(notification:)),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)
}

@objc func applicationDidBecomeActive(notification: NSNotification) {
    // do something
}

Update for Swift 4.2:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc func applicationDidBecomeActive(notification: NSNotification) {
    // Application is back in the foreground

    print("active")
}
4
  • 2
    selector: #selector(applicationDidBecomeActive) is more correct ;)
    – Lucas Leon
    Jul 14, 2016 at 14:44
  • @LucasLeon, was just about to post the same thing. Using strings is basically deprecated in Swift 2.2 and they're thinking of removing that ability entirely in Swift 3. Aug 28, 2016 at 16:14
  • Feel free to edit my answer, this was written a (relatively) long time ago! Sep 11, 2016 at 5:01
  • This code works well in regular ViewController. However when I try doing the same from ViewController which is part of NavigationViewController - then it doesn't work. Selector function isn't called. Is there a diference? Jan 3, 2019 at 13:40
21

Swift 3:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(applicationDidBecomeActive(_:)),
    name: NSNotification.Name.UIApplicationDidBecomeActive,
    object: nil)



func applicationDidBecomeActive(_ notification: NSNotification) {
    // do something
}

Note: Don't forget to remove the observer

5
  • As a newcomer to Swift; wouldn't you want to make applicationDidBecomeActive above private?
    – Jonny
    Mar 21, 2017 at 4:20
  • that's totally up to you, Johnny and to what you need
    – Dani
    Mar 21, 2017 at 12:24
  • 1
    OK. I come from a ObjC/C++ etc background where the "default flow" is to hide things away as much as possible, until someone else needs it and only after much begging you might open it up. Some people call it low coupling, I guess. Well, it's a longer discussion which probably already exists somewhere else.
    – Jonny
    Mar 22, 2017 at 1:42
  • Do you still need to remove the observer? useyourloaf.com/blog/… May 5, 2017 at 4:28
  • better safe than sorry
    – Dani
    May 5, 2017 at 12:17
2

You cannot use applicationDidBecomeActive in viewController; it is not a method for that class.

However, you can use applicationDidBecomeActive method in AppDelegate to call any methods in your view controller that you feel are important upon launch. Just keep a pointer to your controller so the App Delegate can reach it.

What those methods might be in your view controller is entirely up to you and the details of your program. Maybe it means calling a custom update method in your view controller or whatever else you feel is necessary.

You could also use NSNotificationCenter as outlined here, with many system notifications available for application launch: http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html

However, relying heavily on NSNotificationCenter is in my opinion a good way for an app to be come disorganized. If you call everything from your main methods in the AppDelegate only, you can always refer to that method to know exactly what your app is doing upon launch. If instead you use NSNotificationCenter, you could have actions spread across many classes/objects and it can be harder to track down what is going on. Since you mentioned multiple controller objects, I think it is more streamlined and organized to call everything from applicationDidBecomeActive rather than register each viewcontroller for the same notification.

2

update for swift 5

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

    }
   // remove the observer 
   deinit {

       print("Receiver teardown")

       NotificationCenter.default.removeObserver(self)

   }

    @objc func applicationDidBecomeActive(notification: NSNotification) {
        // Application is back in the foreground

        print("applicationDidBecomeActive")
    }

}
2
  • 1
    How do I remove the observer there ?
    – CuriousMan
    Sep 8, 2021 at 16:29
  • 1
    @RaviMan remove the observer deinit { print("Receiver teardown") NotificationCenter.default.removeObserver(self) }
    – Zgpeace
    Sep 11, 2021 at 4:57
0

just Use NotificationCenter in your UIViewController :

NotificationCenter.default.addObserver(self, 
selector: #selector(applicationWillResignActive), 
name: UIApplication.willResignActiveNotification, 
object: nil)
-8

Thank you all for answering my question.
But I found easier way to use applicationDidBecomeActive in UIViewController.

@implementation AppDelegate

-(void)applicationDidBecomeActive:(UIApplication *)application
{
    UIViewController<MyAppDelegate> *topViewController = (UIViewController<MyAppDelegate> *)navigationController.topViewController;
    if ([topViewController respondsToSelector:@selector(MyApplicationDidBecomeActive)]) {
        [topViewController MyApplicationDidBecomeActive];
    }
}
@end

@protocol MyAppDelegate
@optional
-(void)MyApplicationDidBecomeActive;
@end
2
  • 2
    This design will cause increase code complexity and create tighter coupling which could causing difficulties in debugging issues or making future changes.
    – DBD
    Aug 5, 2013 at 19:09
  • then imagine that you have 20 screens with animations and you want repeat this behaviour for them too....
    – wm.p1us
    May 16, 2018 at 5:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.