UIViewController visible callback

2019-02-15 05:04发布

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条回答
我只想做你的唯一
2楼-- · 2019-02-15 05:48

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-15 06:01

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.

查看更多
登录 后发表回答