Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController visible callback

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 Answers

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.

like image 115
rasmus Avatar answered Jul 07 '26 16:07

rasmus


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.

like image 24
Jim Avatar answered Jul 07 '26 15:07

Jim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!