0

У меня есть NSObject, который содержит выгрузку. Одним из свойств является fileProgress (float).Обновление cellForRowAtIndexPath progressView

Прогресс обновляется через NSURLSessionDelegateMethod по названию URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend.

Загружаемые объекты обновляются с использованием taskIdentifier.

В другом классе у меня есть UITableView с пользовательским UITableViewCell, который имеет progressView. Я хотел бы обновить progressView с текущим fileProgress.

Когда загрузка завершена в классе NSObject, загрузка удаляется и вызывается метод делегата, чтобы делегаты знали, что произошло изменение количества очередей. По мере того, как выгружаете, кадры из представлений прогресса меняются на тот момент времени.

Как передать ссылку на текущий просмотр проходов ячеек, чтобы сделать обновление ?

Я попытался добавить к моему cellForRowAtIndexPath , но это не работает.

[[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
     cell.progressView.progress = item.fileProgress; 
     cell.lblProgress.text = [NSString stringWithFormat:@"%.1f%%", (item.fileProgress * 100) ]; 
    }]; 

Я любопытное потерял здесь. Любая помощь?

Загрузить Item

@interface AMUploadItem : NSObject <NSCoding> 
    @property float fileProgress; //The fractional progress of the uploaded; a float between 0.0 and 1.0. 
@property (nonatomic, strong) NSURLSessionUploadTask *uploadTask; //A NSURLSessionUploadTask object that will be used to keep a strong reference to the upload task of a file. 
@property (nonatomic) unsigned long taskIdentifier; 
    @end 

Пользовательские TableViewCell.h (Empty .m)

@interface ItemTableViewCell : UITableViewCell 
@property (weak, nonatomic) IBOutlet UILabel *lblProgress; 
@property (weak, nonatomic) IBOutlet UIProgressView *progressView; 
@end 

Table View Controller

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    _manager = [AMPhotoManager sharedManager]; 
    _manager.delegate = self;  

} 

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


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

    static NSString *simpleTableIdentifier = @"cellUpload"; 

    ItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

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

    AMUploadItem * item = [_manager listImagesInQueue][indexPath.row]; 

//THIS DOENS'T WORK 
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
     cell.progressView.progress = item.fileProgress; 
     cell.lblProgress.text = [NSString stringWithFormat:@"%.1f%%", (item.fileProgress * 100) ]; 
    }]; 

    return cell; 
} 

Класс менеджера просто содержит массив AMItemUploads и NSURLSessionUploadTask delegaes.

ответ

0

Это может быть излишним для вашей ситуации, но вот что я сделал в подобной ситуации. Передача ссылок на представления/ячейки опасна, так как передача может истекать или устаревать из-за взаимодействия пользователя. Вместо этого вы должны передавать уникальные идентификаторы в представления/ячейки, а затем искать их по мере необходимости, чтобы обновить их прогресс. Пользователи становятся нетерпеливыми, ожидая завершения передачи, и предполагают, что они могут удалять файлы и другие неприятные вещи во время ожидания.

// this is pseudo code at best 
    URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend 
    { 
      NSString *uniqueID = <something unique from your NSURLSession > 

      [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
       // assuming you can get the global instance of your controller here. 
       [myController updateProgress:uniqueID]; 

    } 

- (void) updateProgress: (NSString *)uniqueID 
{ 
       NSArray *filesDataSource = <get your dataSource here> ; 
       for (ContentTableRow *fileRow in filesDataSource) 
       {    
       if ([fileRow.uniqueID isEqualToString: uniqueID]) 
       { 
        // update progress 
       } 
       } 
      } 
} 

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

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