问题
I'm trying to upload 2 images(one at a time)using NSURLSessionTask.
- (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];
}
}
How can I use a single progress bar to show the progress in case of 2 image uploads ?
回答1:
The best way is to use NSProgress
which allows you to roll-up child NSProgress
updates into one.
So define a parent
NSProgress
:@property (nonatomic, strong) NSProgress *parentProgress;
Create the
NSProgress
and tell theNSProgressView
to observe it:self.parentProgress = [NSProgress progressWithTotalUnitCount:2]; self.parentProgressView.observedProgress = self.parentProgress;
By using
observedProgress
of theNSProgressView
, when theNSProgress
is updated, the correspondingNSProgressView
will automatically be updated, too.Then, for the individual requests, create individual child
NSProgress
entries that will be updated, e.g.:self.child1Progress = [NSProgress progressWithTotalUnitCount:totalBytes1 parent:self.parentProgress pendingUnitCount:1];
and
self.child2Progress = [NSProgress progressWithTotalUnitCount:totalBytes2 parent:self.parentProgress pendingUnitCount:1];
Then, as the individual network requests proceed, update their respective
NSProgress
with the total bytes thus far:self.child1Progress.completedUnitCount = countBytesThusFar1;
The updating of the completedUnitCount
of the individual child NSProgress
objects will automatically update the fractionCompleted
of the parent NSProgress
object, which, because you're observing that, will update your progress view accordingly.
Just make sure that the totalUnitCount
for the parent to be equal to the sum of the pendingUnitCount
of the children.
来源:https://stackoverflow.com/questions/36615525/one-progress-bar-for-multiple-file-upload