my problem is this:
I want to show ProgressView for files downloading.For some reason the ProgressView gradually rises, showing how much file is already downloaded , and just immediately fills up when files are still not downloaded! What do I need to fix or how to implement it?
Here is my source code:
- (IBAction)download:(id)sender {
// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
progressSlider.progress = 0.0;
for (i=0;i<=7;i++) {
//Updating progressView and progressLabel
progressLabel.text = [NSString stringWithFormat:@"Загружено: %d из 7",i];
progressView.progress = (float)i/(float)7;
NSString *filePath = [NSString stringWithFormat:@"%@/avto-0-%d.html", [paths objectAtIndex:0],i];
// Download and write to file
NSString *mustUrl = [NSString stringWithFormat:@"http://www.mosgortrans.org/pass3/shedule.php?type=avto&%@", [listOfAvtoUrl objectAtIndex:i]];
NSURL *url = [NSURL URLWithString:mustUrl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
}
I think that it is related to threads and how the main thread will refresh the view.
Two cases can occur:
You are on the main thread when calling this method
In such case, you do not allow the main thread to execute refresh routines. Move all this download to a background queue using GCD, and call back the main thread like explained in pt.2.
To put everything in a background queue, you could call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
// your download code goes here
});
Or, You are already on the background thread, then use the following lines to call back to the main thread:
dispatch_async(dispatch_get_main_queue(), ^ {
progressView.progress = (float)i/(float)7;
});
Final answer:
- (IBAction)download:(id)sender {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
// Determile cache file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
progressSlider.progress = 0.0;
for (i=0;i<=7;i++) {
//Updating progressView and progressLabel
progressLabel.text = [NSString stringWithFormat:@"Загружено: %d из 7",i];
dispatch_async(dispatch_get_main_queue(), ^ {
progressView.progress = (float)i/(float)7;
});
NSString *filePath = [NSString stringWithFormat:@"%@/avto-0-%d.html", [paths objectAtIndex:0],i];
// Download and write to file
NSString *mustUrl = [NSString stringWithFormat:@"http://www.mosgortrans.org/pass3/shedule.php?type=avto&%@", [listOfAvtoUrl objectAtIndex:i]];
NSURL *url = [NSURL URLWithString:mustUrl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
});
}