I was looking for an indefinite animation technique for my loading animation. The user clicks login, and whilst the JSON stuff is taking care of itself, the spinner spins and then eventually presents a new view controller or login error. I found a great code snippet given by Nate.
The code is given by:
// an ivar for your class:
BOOL animating;
- (void) spinWithOptions: (UIViewAnimationOptions) options {
// this spin completes 360 degrees every 2 seconds
[UIView animateWithDuration: 0.5f
delay: 0.0f
options: options
animations: ^{
self.imageToMove.transform = CGAffineTransformRotate(imageToMove.transform, M_PI / 2);
}
completion: ^(BOOL finished) {
if (finished) {
if (animating) {
// if flag still set, keep spinning with constant speed
[self spinWithOptions: UIViewAnimationOptionCurveLinear];
} else if (options != UIViewAnimationOptionCurveEaseOut) {
// one last spin, with deceleration
[self spinWithOptions: UIViewAnimationOptionCurveEaseOut];
}
}
}];
}
- (void) startSpin {
if (!animating) {
animating = YES;
[self spinWithOptions: UIViewAnimationOptionCurveEaseIn];
}
}
- (void) stopSpin {
// set the flag to stop spinning after one last 90 degree increment
animating = NO;
}
When the user clicks 'login' the startSpin
method is called, and the JSON stuff is sent. In my JSON post method I have this:
if(success == 1) {
//Present the new view controller
}
else {
[self performSelectorOnMainThread:@selector(stopSpin) withObject:nil waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(hideAnimation) withObject:nil waitUntilDone:NO];
}
This animation method has worked great for an uploading page I use later in my app. However, for this application, it only spins 180 degrees then stops. Then the next page/error eventually loads after a time interval of the inanimate image. Does anybody have any idea as to why this is happening? I dont think it is anything to do with the view controller part because it stops spinning even when the login has failed (no view controller to be presented). I call my startSpin
method on the click of a button using:
[self performSelectorOnMainThread:@selector(showAnimation) withObject:nil waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(startSpin) withObject:nil waitUntilDone:NO];
Where show animation is just a method which un-hides the view.
Any thoughts appreciated.