【问题标题】:Set the progress to UIProgressView when upload with NSURLConnection使用 NSURLConnection 上传时将进度设置为 UIProgressView
【发布时间】:2012-10-08 04:36:14
【问题描述】:

我正在尝试刷新 UIProgressView 中的进度条,以获取 NSURLConnection 的上传请求。目标是在上传图片时刷新进度条。经过几次搜索,我设法使用我的连接委托的didSendBodyData 来检查进度:

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    if([self.delegate respondsToSelector:@selector(progressView)])
    {
        self.delegate.progressView.progress = (totalBytesWritten / totalBytesExpectedToWrite) * 100.0;
    }
}

一切正常,但问题是这个方法只被调用一次......所以酒吧停留在 0% 片刻,然后立即进入 100% 没有中间。我尝试(在 iPhone 上使用 iOS6 开发者工具)将我的连接设置为慢速边缘连接,以判断是否只是我的上传速度太快,但不,上传需要一段时间为 0,然后立即转到 100% 并且该方法只被调用一次...

有什么想法吗?谢谢 !我不知道如何解决这个问题......

【问题讨论】:

    标签: ios ios5 ios6 nsurlconnection nsurlconnectiondelegate


    【解决方案1】:

    您应该认真阅读有关数值类型的 C 教程。 大概totalBytesWrittentotalBytesExpectedToWrite 都是整数类型,因此将它们相除会导致截断 - 即小数部分结果将消失。除非结果为 100%,否则整数部分始终为 0,因此所有这些除法将导致零。尝试将一个或两个变量转换为 floatdouble 以获得合理的结果。

    另外,UIProgressView 默认不接受 0 到 100 之间的值,而是 0 到 1 之间的值。总而言之,你应该写

    self.delegate.progressView.progress = ((float)totalBytesWritten / totalBytesExpectedToWrite);
    

    它应该可以正常工作。

    编辑:问题是你尝试上传的数据太小,不需要分解成更小的块,所以只需要调用一次这个方法.如果你提供了大量的数据,那么它只能分块发送,所以进度处理回调会被多次调用。

    【讨论】:

    • 谢谢你的回答,是的,我明白我的错误在这里,但问题不是这个......我的线路当然是错误的,但问题是当我NSLog 调用检查bytesWrittentotalBytesWrittentotalBytesExpectedToWrite的方法,我清楚地看到该方法只调用了一次并且所有值都等于totalBytesWritten,所以没有进展,只有0到100...
    • @FabienParseError 可能是数据太小,无法分割成更小的块。
    • 谢谢@H2CO3!就是这样!我尝试同时上传10张图片,现在进度条显示中间;)对不起,谢谢你的帮助!
    猜你喜欢
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多