问题
I'm using a POST request to upload some data to a server, and I'm trying to update the UIProgressView's progress based on the totalBytesWritten
property of the didSendBodyData
method of NSURLConnection
. Using the below code, I don't get a proper updating of the progress view, it's always 0.000 until it finishes. I'm not sure what to multiply or divide by to get a better progress of the upload.
I'd appreciate any help offered! Code:
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSNumber *progress = [NSNumber numberWithFloat:(totalBytesWritten / totalBytesExpectedToWrite)];
NSLog(@"Proggy: %f",progress.floatValue);
self.uploadProgressView.progress = progress.floatValue;
}
回答1:
You have to cast the bytesWritten and the bytesExpected as float
values to divide.
float myProgress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
progressView.progress = myProgress;
Otherwise you are will get either a 0 or some other number as a result of dividing 2 integers.
ie: 10 / 25 = 0
10.0 / 25.0 = 0.40
Objective-C provides the modulus
operator %
for determining remainder and is useful for dividing integers.
回答2:
You code looks good. Try to use a big file like 20 MB to 50 MB for upload.
If you use a UIProgressView you can set the progress in the connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: method like this:
float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
progressView.progress = progress/total;
In simple code:
progressView.progress = (float)totalBytesWritten / totalBytesExpectedToWrite
Hope it will help you.
来源:https://stackoverflow.com/questions/24189092/nsurlconnection-didsendbodydata-progress