Search code examples
swiftuiviewbackgroundforegroundanimatewithduration

Resume animateWithDuration .Repeat after return to foreground


Unfortunately, I found out that UIView.animateWithDuration stops once you minimize your app to homescreen and does not resume once you bring it back to the foreground.

I've spent the last hour trying to figure out how to solve this (by detecting background/foreground switching) and resulted to adding an observer. I did it and successfully detected it with a debugging message in console; however, I'm sure of how to resume the animation(s) in my view(s). What is the correct way to pause/resume or even restart the animation when the app is loaded back into the foreground?

ViewController.swift

class ViewController: UIViewController {
    func cameBackFromSleep(sender : AnyObject) {
        // Restart animation here or resume?
        print ("If you can see this, congrats... observer works :-)")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Observer to detect return from background
        NSNotificationCenter.defaultCenter().addObserver(    self,    selector: #selector(ViewController0.cameBackFromSleep(_:)),    name: UIApplicationDidBecomeActiveNotification,    object: nil    )

        // Add a label
        let label = UILabel(frame: CGRectMake(0, 600 , 200, 200 ))
        label.text = "test message"
        label.font = UIFont.boldSystemFontOfSize(12)
        label.sizeToFit()
        self.view.addSubview(label)

        // Animation to move label
        func animateText() {
            UIView.animateWithDuration(2.0, delay: 0.0, options: [ .Autoreverse, .Repeat, .CurveEaseInOut, .BeginFromCurrentState], animations: {
                label.alpha = 0.3
                label.frame.origin.x = ((global.maxwidth/2) * -1) 
                }, completion: { finished in
                    if finished {
                        label.frame.origin.x = 0.0
                    }
            })
        }

        // This guy here stops once you minimize the app to background
        animateText()
    }
}

Solution

  • Put animateText() inside comeBackFromSleep(_:). I believe that resuming an animation is kinda hard so just restart it.

    The behavior somewhat makes sense because of this (you can take a look yourself at the AppDelegate's methods):

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    

    It states that you should refresh the UI (which includes animations). So it's normal behavior for the animations to stop after you put an app in the background.