1

我正在尝试使用 NSURLSessionTask 上传 2 张图片(一次一张)。

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
if (self.imageName1 != nil && self.imageName2 != nil) 
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        {
            // Calculate total bytes to be uploaded or the split the progress bar in 2 halves
        }
    }
    else if (self.imageName1 != nil && self.imageName2 == nil)
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        [self.progressBar1 setProgress:progress animated:YES];
    }
    else if (self.imageName2 != nil && self.imageName1 == nil)
    {
        float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
        if (progress != 1.00)
        [self.progressBar2 setProgress:progress animated:YES];  
    }
}

如果上传 2 张图片,如何使用单个进度条显示进度?

4

1 回答 1

1

最好的方法是使用它允许您将子更新NSProgress汇总为一个。NSProgress

  1. 所以定义一个父母NSProgress

    @property (nonatomic, strong) NSProgress *parentProgress;
    
  2. 创建NSProgress并告诉NSProgressView观察它:

    self.parentProgress = [NSProgress progressWithTotalUnitCount:2];
    self.parentProgressView.observedProgress = self.parentProgress;
    

    通过使用observedProgressNSProgressViewNSProgress更新时,对应的NSProgressView也会自动更新。

  3. 然后,对于单个请求,创建NSProgress将被更新的单个子条目,例如:

    self.child1Progress = [NSProgress progressWithTotalUnitCount:totalBytes1 parent:self.parentProgress pendingUnitCount:1];
    

    self.child2Progress = [NSProgress progressWithTotalUnitCount:totalBytes2 parent:self.parentProgress pendingUnitCount:1];
    
  4. 然后,随着各个网络请求的进行,NSProgress用迄今为止的总字节数更新它们:

    self.child1Progress.completedUnitCount = countBytesThusFar1;
    

completedUnitCount单个子对象的更新NSProgress将自动更新fractionCompletedNSProgress对象的 ,因为您正在观察,它将相应地更新您的进度视图。

只需确保totalUnitCount父级的 等于pendingUnitCount子级的总和即可。

于 2016-04-14T07:33:49.900 回答