2014-01-17 5 views
0

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

// 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; 
    } 
} 
+0

Вы можете попробовать с этой ссылке: http://stackoverflow.com/questions/12207288/correct-way-to-show-downloadable-content-in-uitableview-with-progressbar-etc – Harunmughal

ответ

0

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

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

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

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

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

self.downloadManager.maxConcurrentDownloads = 4; 

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

 Смежные вопросы

  • Нет связанных вопросов^_^