Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Update UIView from Block Code in Objective C

I am trying to Update a label for showing the Progress of the File to be downloaded using the AFNetworking Framework. The problem is that when i set the percentage to the label in the setProgressiveDownloadProgressBlock the label is updated only when the download starts and when download completes.

 __weak MTCViewController *weakSelf= self; 
[_operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
        float percent = (float)(totalBytesRead / totalBytesExpectedToReadForFile)*100;;
       // [weakSelf updateProgress:percent];
        [weakSelf updateText:[NSString stringWithFormat:@"Progress = %f",percent]];
    }];
    [_operation start];

Plus when i remove the label update code the block seems to be updating correctly

like image 755
Quamber Ali Avatar asked Jun 03 '13 13:06

Quamber Ali


1 Answers

You need to call all UI changes on the main thread. So, calculate the percentage and then dispatch the code that updates the UI from the main thread:

__weak MTCViewController *weakSelf= self; 
[_operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
    float percent = ((float)totalBytesRead / (float)totalBytesExpectedToReadForFile)*100;
      dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf updateText:[NSString stringWithFormat:@"Progress = %f", round(percent)]];
      });
}];
[_operation start];
like image 128
Marcel Avatar answered Oct 17 '22 07:10

Marcel