NSURLConnection didSendBodyData progress



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

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

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

您必须将bytesWritten和bytesExpected转换为float值以进行划分。

float myProgress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
progressView.progress = myProgress;

否则,你将得到一个0或其他数字作为两个整数除以的结果。

ie: 10 / 25 = 0

10.0 / 25.0 = 0.40

Objective-C提供了modulus运算符%用于确定余数,并用于除法整数。

您的代码看起来不错。尝试使用20到50 MB的大文件进行上传。

如果你使用UIProgressView,你可以在connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:方法中设置进度,就像这样:

 float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
 float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
 progressView.progress = progress/total;

在简单代码中:

progressView.progress = (float)totalBytesWritten / totalBytesExpectedToWrite

最新更新