Обновление панели uiprogress в строках ячеек

Я создаю приложение, которое позволит пользователям загружать и читать выпуски журнала. Я использую Download Manager framework created by Robert Ryan и изменил тестовый проект, поставляемый с фреймворком, чтобы он работал в моем проекте (с фреймворком проблем нет). В каждой строке таблицы есть изображение обложки задачи (UIImageView), метка загрузки/чтения (UILabel), метка даты выпуска (UILabel) и индикатор выполнения (UIProgressView) — все это свойства UITableViewCell. Когда пользователь нажимает на строку, он инициирует процесс загрузки задачи, что отражается на индикаторе выполнения; после завершения загрузки индикатор выполнения скрывается, а заголовок метки «Загрузка» изменяется на «Читать», а когда пользователь снова нажимает на строку, чтобы прочитать загруженный журнал, он открывает средство просмотра PDF в формате viewcontroller. Я еще не добавил функцию чтения. Все это прекрасно работает за исключением того, что в качестве теста у меня есть 2 номера журнала в таблице каждый подряд со своим ``. Когда я нажимаю на первую строку, индикатор выполнения отражает ход загрузки, и он работает нормально. Однако, когда я нажимаю на вторую строку, ход загрузки отражается в индикаторе выполнения первой строки, а не во второй строке, как ожидалось (индикатор выполнения остается статическим). Он загружает второй журнал, и все работает нормально. Это просто неожиданное поведение, когда ход загрузки второй строки отражается на индикаторе выполнения в первой строке. Мне все еще нужно оптимизировать код и очистить его, но соответствующие разделы кода приведены ниже:

// optional method to indicate progress of individual download
//
// In this view controller, I'll update progress indicator for the download.

- (void)downloadManager:(DownloadManager *)downloadManager downloadDidReceiveData: (Download *)download;
{
    for (NSInteger row = 0; row < [downloadManager.downloads count]; row++)
    {
        if (download == downloadManager.downloads[row])
        {
            [self updateProgressViewForIndexPath:[NSIndexPath indexPathForRow:row  inSection:0] download:download];
            break;
        }
    }
}

#pragma mark - Table View delegate and data source methods

// our table view will simply display a list of files being downloaded

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return[jitsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{

    static NSString *CellIdentifier = @"DownloadCell";

    DownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[DownloadCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    } 


    jits * jitsInstance = nil;

    jitsInstance = [jitsArray objectAtIndex:indexPath.row];

    cell.issue.text = jitsInstance.issue;

    NSString * myCoverURL = [NSString stringWithFormat:@"%@", jitsInstance.coverimage];

    UIImage* myImage = [UIImage imageWithData:
                        [NSData dataWithContentsOfURL:
                         [NSURL URLWithString: myCoverURL]]];


    cell.coverimage.image = myImage;



    [cell.progressView setProgress:0];


    NSString * myURL = [NSString stringWithFormat:@"%@", jitsInstance.url];

    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) objectAtIndex:0];

    NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:@"downloads"];

    NSString * fileName = [[NSString alloc]initWithFormat:@"%@", [myURL lastPathComponent]];

    NSString* foofile = [downloadFolder stringByAppendingPathComponent:fileName];

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

    NSLog(@"Search file path: %@", foofile);

    if (!fileExists) {
        [cell.downloadButton setTitle:@"Download" forState:normal];
        [cell.progressView setHidden:NO];
        NSLog(@"File does not exist!");

    }
    else if (fileExists){
        NSLog(@"File exist!");
        [cell.downloadButton setTitle:@"Read" forState:normal];
        [cell.progressView setHidden:YES];
    }

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES)[0];

    NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:@"downloads"];

    jits * jitsInstance = nil;

    jitsInstance = [jitsArray objectAtIndex:indexPath.row];

    NSString * myURL = [NSString stringWithFormat:@"%@", jitsInstance.url];

    self.downloadManager = [[DownloadManager alloc] initWithDelegate:self];

    self.downloadManager.maxConcurrentDownloads = 4;

    NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:[myURL lastPathComponent]];

    NSURL *url = [NSURL URLWithString:myURL];

    [self.downloadManager addDownloadWithFilename:downloadFilename URL:url];

    self.cancelButton.enabled = YES;

    self.startDate = [NSDate date];

    [self.downloadManager start];

    }

#pragma mark - Table view utility methods

- (void)updateProgressViewForIndexPath:(NSIndexPath *)indexPath download:(Download  *)download
{
    DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:indexPath.row inSection:0]];

    // if the cell is not visible, we can return

    if (!cell)
        return;

    if (download.expectedContentLength >= 0)
    {
        // if the server was able to tell us the length of the file, then update progress  view appropriately
        // to reflect what % of the file has been downloaded

        cell.progressView.progress = (double) download.progressContentLength / (double)    download.expectedContentLength;
    }
    else
    {
        // if the server was unable to tell us the length of the file, we'll change the   progress view, but
        // it will just spin around and around, not really telling us the progress of the  complete download,
        // but at least we get some progress update as bytes are downloaded.
        //
        // This progress view will just be what % of the current megabyte has been  downloaded

        cell.progressView.progress = (double) (download.progressContentLength % 1000000L) / 1000000.0;
    }
}

person bachma0507    schedule 17.01.2014    source источник
comment
Вы можете попробовать эту ссылку: stackoverflow.com/questions/12207288/   -  person Harunmughal    schedule 17.01.2014


Ответы (1)


Я думаю, что ваша проблема может заключаться в следующем коде:

for (NSInteger row = 0; row < [downloadManager.downloads count]; row++)
{
    if (download == downloadManager.downloads[row])
    {
        [self updateProgressViewForIndexPath:[NSIndexPath indexPathForRow:row  inSection:0] download:download];
        break;
    }
}

По сути, это похоже на то, что он находит первую ячейку в массиве загрузок, вызывает updateProgressViewForIndexPath для этой первой найденной ячейки, а затем останавливается. Есть несколько способов решить эту проблему, но первый, который приходит на ум, это когда вы говорите себе обновить ячейку по этому пути индекса, когда оператор if оценивается как true, удалите этот элемент из массива загрузок менеджера загрузки, поэтому в следующий раз его там не будет. Попробуйте и дайте мне знать, если это сработает.

Кроме того, на заметку... Я бы подумал, что вы не хотите делать следующие две строки каждый раз, когда выбирается строка:

self.downloadManager = [[DownloadManager alloc] initWithDelegate:self];

self.downloadManager.maxConcurrentDownloads = 4;

Мне кажется, что это то, что вы хотели бы сделать, возможно, в своем методе инициализации вашего tableView, чтобы это происходило только один раз, а не каждый раз, когда пользователь нажимает на строку. Возможно, вы пытаетесь каждый раз создавать и устанавливать в качестве свойства новый менеджер загрузок? Мне это кажется неортодоксальным. Если бы у меня был доступ к проекту, я думаю, что мог бы лучше помочь в отладке. Есть шанс, что вы захотите поделиться проектом, если мой ответ не помог?

person Mike    schedule 17.01.2014