3

I am developing an iOS application where need to do some stuff when I have Internet connection and other, when I haven't. If I haven't at some point I will show a message to the user to give me internet and come back. The question it is how to detect the following situation:

  • the user press the Home button twice, goes to multitasking , Settings and will connect to internet
  • the user comes back with multitasking to my app, but doesn't press anything

I know I will get callbacks to the AppDelegate:

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

but the code ( it is not started by me) it is very big, and I don't want to handle there the UIViewController needs, if there is any alternative.

My UIViewController's - (void)viewDidAppear:(BOOL)animated it isn't called when the user came back.

screenshot

The breakpoint it is not hited for sure!

Any usable ideas, except in AppDelegate?

2 Answers2

7

You can use the notification center to listen to applicationDidEnterBackground within the view controller:

[[NSNotificationCenter defaultCenter] addObserver: self
                                      selector: @selector(handleEnteredBackground:) 
                                      name: UIApplicationDidEnterBackgroundNotification
                                      object: nil];

Do this in viewDidLoad. Similarily for applicationDidBecomeActive.

Don't forget to remove yourself as an observer in viewDidUnload.

rasmus
  • 3,136
  • 17
  • 22
  • +1 probably will be accepted too, although there are plenty notification in the viewcontroller, but I really don't want to touch AppdDlegate. –  Sep 04 '12 at 15:48
  • it is working perfectly, exactly as I needed. Worth 10 up votes for me, big thanks –  Sep 04 '12 at 16:04
  • 1
    You must remove yourself as an observer in `dealloc`. There is no guarantee that `viewDidUnload` will ever be called. You *can* do it in both functions. – NJones Sep 04 '12 at 16:31
2

The application delegate is the correct place to be handling application state changes, but just because that is the case, it doesn't mean you must put all the logic that is triggered by the application state change in there.

Put the logic where it belongs. If it's networking code, that's not in the application delegate and it's not in the view controller, it's in a separate class. Then look into ways of tying the different parts of your application together. In most cases, notifications, KVO and the shared instance pattern are good approaches to take.

Jim
  • 72,985
  • 14
  • 101
  • 108
  • +1 for effort, but it is not helpfull. I told the code is very big, hard to move anything here, lot of memory leaks, and so on. To rewrite is more than 6 month, I don't want to debug again 1 week for 1 changes. –  Sep 04 '12 at 15:51