Search code examples
iosswiftuibuttonuiviewanimationnotificationcenter

UIButton becomes Inanimate after the user presses Home Button


I have a UIButton called findButton that has a pulsing or breathing animation. When testing the app in the simulator and device, everything works perfectly until I click the Home Button while the animation is occurring. If I do press the Home Button and then reopen the app, the animation is no longer occurring.

I tried various answers found on this site and none have worked. I've tried using Extensions and NotificationCenter, but nothing that has supposedly worked for people in the past is working for me. Here's a look at the animation code that works perfectly before the Home Button is pressed:

override func viewWillAppear(_ animated: Bool) {

    UIView.animate(withDuration: 1.0,
                   delay: 0,
                   options: [.autoreverse, .repeat, .allowUserInteraction],
                   animations: {
                    self.findButton.transform = CGAffineTransform(scaleX: 1.175, y: 1.175)}, completion: nil)
} 

I'm wondering if perhaps I need to pause the animation before it goes into the background?

UPDATE: I was able to get the 'findButton' to work when pressed by moving the animations that occur AFTER it is pressed. I created a new VC and class and put findButton IBAction with the post-click animations there.

Unfortunately, findButton is still inanimate after returning from background. I am hoping that NoticationCenter will work now that I moved the post-click animations out of the first VC.


Solution

  • @pooja's answer will definitely take you down the right path. But if you are using iOS 12, Xcode 10, Swift 4.2, then you will run into some errors when implementing NotificationCenter. Try @pooja's code, but make these changes:

    NotificationCenter.default.addObserver(self, selector:#selector(doSomethingBefore), name: UIApplication.didEnterBackgroundNotification, object: nil)
    
    NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: UIApplication.willEnterForegroundNotification, object: nil)