theflarenet theflarenet - 2 years ago 292
Swift Question

Resume animateWithDuration .Repeat after return to foreground

Unfortunately, I found out that

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?


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

override func 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)

// 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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download