I’m downloading some pictures and have created a progress bar. I’m using asynchronous mode with NSURLConnection and initiate about 15 pictures downloads at the same time. During the initiation i call didStartLoadImages and the bar is successfully set to 0 width on the screen.
Now the problem start, when one of the images is completed it will call didLoadImageWithTotalPercentCompleted: and update the bar with the current percent. It works perfectly and the logs write nicely Updating frame to: 20% etc.. But the User Interface doesn’t update UNTILL all the images are completed?
I just notice that the main thread is blocked even tho it’s asynchronous?
Connection.m
-(void)loadImage:(NSString*)imageName numberOfImagesInSecquence:(int)nrOfImages {
NSString *url = [NSString stringWithFormat:@"https://xxx.xxx.xxx.xxx/~%@/files/%@",site,imageName];
/* Send URL */
NSURL *urlToSend = [[NSURL alloc] initWithString:url];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend];
theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
self.receivedData = [NSMutableData data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
connectionIsLoading = NO;
[[self delegate] didLoadImagesWithProcent:((float)1 - ((float)[imageArray count] / (float)nrOfImages)) *(float)100];
}
MainViewController.m
-(void)didStartLoadImages {
/* Sets progress bar to 0% */
[progressBar setBarWithPercent:0];
}
-(void)didLoadImageWithTotalPercentCompleted:(int)percent {
if (percent == 100) {
/* Done */
} else {
[progressBar setBarWithPercent:percent];
}
}
ProgressBar.m
-(void)setBarWithPercent:(float)percent {
int maxSizeOfBar = 411;
[UIView beginAnimations:@"in" context:NULL];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationBeginsFromCurrentState:YES];
CGRect frame = bar.frame;
frame.size.width = maxSizeOfBar * (percent / 100) + 10;
bar.frame = frame;
NSLog(@"Updating frame to: %i",percent);
[UIView commitAnimations];
}
This may be a problem with integer math truncation. Change your percentage value to a float or CGFloat instead of an int, and for all of your numbers write them like 100.0f instead of 100 to force C to treat them as floats instead of integers.
Basically, in C if you do 1/2 it doesn’t give you 0.5, it gives you 0 because it uses integer math, and 2 doesn’t go into 1 a whole number of times. So when calculating a percentage, you really want to use floats because (1/100) * x will always be zero, but (1.0f/100.0f) * x will work correctly.