iosobjective-cnsurlconnectionuiprogressviewnsurlconnectiondelegate

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

Solution

  • 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.