So I have done animations based with the help of method animateWithDuration but i need to stop animation when app goes in background and resume when app comes back in foreground.
Is there a way i can achieve this:-
My animations : label fade in fade out after certain intervals;
- (void)viewDidLoad {
[super viewDidLoad];
[self MyLabelAnimation];
}
- (void)MyLabelAnimation {
self.myLabel.text = @"Text 1";
[UIView animateWithDuration:0.3 animations:^{
self.myLabel.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 delay:2.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.myLabel.alpha = 0.0;
} completion:^(BOOL finished) {
self.myLabel.text = @"Text 2";
[UIView animateWithDuration:0.3 animations:^{
self.myLabel.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 delay:2.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.myLabel.alpha = 0.0;
} completion:^(BOOL finished) {
self.myLabel.text = @"Text 3";
[UIView animateWithDuration:0.3 animations:^{
self.myLabel.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 delay:2.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.myLabel.alpha = 0.0;
} completion:^(BOOL finished) {
self.myLabel.text = @"Text 4";
[UIView animateWithDuration:0.3 animations:^{
self.myLabel.alpha = 1.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.0 delay:4.8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.myLabel.alpha = 0.0;
} completion:^(BOOL finished) {
[self MyLabelAnimation];
}];
}];
}];
}];
}];
}];
}];
}];
}
Since your animation appears to be a sequence of several smaller sub-animations repeated ad infinitum, you could keep track of where you are in the animation loop at all times, stop the animation when your app becomes inactive, and restart the animation when your app becomes active again.
[Edit: sample code and explanations added below.]
In
ViewController.m
:globalStage
andanimationIsActive
are used to keep track of where we are in the animation and whether or not the animation is running.viewWillAppear:
we ask to be notified when the app becomes active or inactive. When these events occur, our methodsdidBecomeActive:
orwillResignActive:
are called. These two methods are where we (re)start and stop our animations.UIApplication
notifications inviewDidDisappear:
.