在Objective-C中下载某些文件的进度视图

时间:2012-11-22 12:33:40

标签: objective-c progress-bar uiprogressview downloading

我的问题是:

我想显示ProgressView的文件下载。由于某种原因,ProgressView逐渐上升,显示已经下载了多少文件,并且在文件仍未下载时立即填满!我需要修复什么或如何实现它?

这是我的源代码:

- (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];
    }
 }

1 个答案:

答案 0 :(得分:2)

我认为它与线程以及主线程如何刷新视图有关。

可能发生两种情况:

调用此方法时,您处于主线程

在这种情况下,您不允许主线程执行刷新例程。使用GCD将所有这些下载移动到后台队列,并回调主线程,如第2节中所述。

要将所有内容放入后台队列,您可以调用:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
        // your download code goes here


    });

或者,您已经在后台线程中,然后使用以下行回调主线程:

dispatch_async(dispatch_get_main_queue(), ^ {
            progressView.progress = (float)i/(float)7;
        });

最终答案:

- (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];
    }
});
 }