0

我的问题是这样的:

我想显示 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];
    }
 }
4

1 回答 1

2

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

可能出现两种情况:

调用此方法时您在主线程上

在这种情况下,您不允许主线程执行刷新例程。使用 GCD 将所有这些下载移动到后台队列,并按照 pt.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];
    }
});
 }
于 2012-11-22T12:47:32.037 回答