iOS, Restarting animation when coming out of the background

Stultus picture Stultus · May 18, 2011 · Viewed 22.9k times · Source

when my app comes out of the background the animation has stopped. which is normal. but i want to restart my animation from the current state. how do i do that without my snapping all over the place.

[UIView animateWithDuration:60 delay:0 options:(UIViewAnimationOptionCurveLinear |UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState) animations:^{
    [bg setFrame:CGRectMake(0, 0, 1378, 1005)];
} completion:nil];

i tried putting a set frame in front of the animation but that just makes it snap.

[bg setFrame:CGRectMake(0, 0, 1378, 1005)];

any ideas?

Answer

Ramiro picture Ramiro · Dec 11, 2012

You can add an observer in your class for UIApplicationWillEnterForegroundNotification:

- (void)addNotifications { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; 
}

- (void)applicationWillEnterForeground { 
    [self animate]; 
}

- (void)animate { 
    [bg setFrame:CGRectMake(0, 0, 0, 0)]; 
    [UIView animateWithDuration:60 delay:0 options:(UIViewAnimationOptionCurveLinear |UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState) animations:^{
        [bg setFrame:CGRectMake(0, 0, 1378, 1005)];
    } completion:nil];
}

It is important to set the begin state of the animation (and don't forget to remove the notification observer)