NSURLConnection didSendBodyData进展

klc*_*r89 3 objective-c nsurlconnection uiprogressview ios nsurlconnectiondelegate

我正在使用POST请求将一些数据上传到服务器,我正在尝试根据方法的totalBytesWritten属性更新UIProgressView的进度.使用下面的代码,我没有得到正确的进度视图更新,它总是0.000直到它完成.我不确定要乘以或除以什么来获得更好的上传进度.didSendBodyDataNSURLConnection

我很感激提供任何帮助!码:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*tin 7

您必须将bytesWritten和bytesExpected作为float值进行转换.

float myProgress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
progressView.progress = myProgress;
Run Code Online (Sandbox Code Playgroud)

否则,由于除以2个整数,您将获得0或其他数字.

即: 10 / 25 = 0

10.0 / 25.0 = 0.40

Objective-C为modulus运算符提供了%确定余数的功能,可用于分割整数.