klcjr89
klcjr89

Reputation: 5902

NSURLConnection didSendBodyData progress

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;
}

Upvotes: 3

Views: 2120

Answers (2)

Daddy
Daddy

Reputation: 9035

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.

Upvotes: 7

Ragu
Ragu

Reputation: 412

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.

Upvotes: 2

Related Questions