When I call startAnimating on a UIActivityIndicatorView, it doesn't start. Why is this?
[This is a blog-style self-answered question. The solution below works for me, but, maybe there are others that are better?]
If you write code like this:
- (void) doStuff
{
[activityIndicator startAnimating];
...lots of computation...
[activityIndicator stopAnimating];
}
You aren't giving the UI time to actually start and stop the activity indicator, because all of your computation is on the main thread. One solution is to call startAnimating in a separate thread:
- (void) threadStartAnimating:(id)data {
[activityIndicator startAnimating];
}
- (void)doStuff
{
[NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
...lots of computation...
[activityIndicator stopAnimating];
}
Or, you could put your computation on a separate thread, and wait for it to finish before calling stopAnimation.
I usually do:
[activityIndicator startAnimating];
[self performSelector:@selector(lotsOfComputation) withObject:nil afterDelay:0.01];
...
- (void)lotsOfComputation {
...
[activityIndicator stopAnimating];
}
This question is quite useful. But one thing that is missing in the answer post is , every thing that takes long time need to be perform in separate thread not the UIActivityIndicatorView. This way it won't stop responding to UI interface.
- (void) doLotsOFWork:(id)data {
// do the work here.
}
-(void)doStuff{
[activityIndicator startAnimating];
[NSThread detachNewThreadSelector:@selector(doLotsOFWork:) toTarget:self withObject:nil];
[activityIndicator stopAnimating];
}
All UI elements require to be on main thread
[self performSelectorOnMainThread:@selector(startIndicator) withObject:nil waitUntilDone:NO];
then:
-(void)startIndicator{
[activityIndicator startAnimating];
}
If needed, swift 3 version:
func doSomething() {
activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
//do some processing intensive stuff
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With