Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIApplicationWillEnterForegroundNotification get called more and more

I am using this function in my view controllers to recognize if the app is active again and to refresh some data:

[[NSNotificationCenter defaultCenter]
            addObserver:self
               selector:@selector(becomeActive:)
                   name:UIApplicationWillEnterForegroundNotification
                 object:nil];

This works for refreshing after getting active, but everytime the app gets back from background to foreground (inactive to active) it calls the function one more time.

So if I closed and opened the app 4 times, the function will be called 4 times!

EDIT: The function will be called this way:

  1. close and open: function called 1 time (that's the way i want it)
  2. close and open: function called 2 times
  3. close and open: function called 3 times
  4. close and open: function called 4 times

But it only have to be called 1 time after getting back in foreground. In some situation the app have to show an alert view after getting active and checking data. This alert view will be shown 4 times when the function will be called 4 times.

In the app delegate this function does nothing, but it is mentioned.

I am using Xcode 4.2 and iOS 5! I also used UIApplicationDidBecomeActive, but it also cause the same problem.

like image 334
user1175122 Avatar asked Mar 29 '26 17:03

user1175122


1 Answers

I don't know at when your adding self as an observer, but every time the app becomes active, you seem to be adding self as an observer, again and again. Thus the multiple calls.

You must only add your view controller as an observer once. Try using the controllers init: method. And, ensure that you remove the view controller as an observer in the dealloc: method.

like image 60
Brad G Avatar answered Apr 01 '26 08:04

Brad G



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!