NSURLSession,上传任务 - 获取实际传输的字节数 [英] NSURLSession, upload task - Get actual bytes transferred

查看:356
本文介绍了NSURLSession,上传任务 - 获取实际传输的字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误报告,说我的iOS应用程序无法在慢速连接上传图像。虽然我的超时可能不够高,但还有另一个问题。

I was getting bug reports that my iOS app failed upload of images on slow connections. While my timeout probably wasn't high enough, there was another issue.

我发现上传进度很快就达到了100%,尽管我可以在Charles看到字节仍然被转移。我使用以下NSURLSession方法:

I found that upload progress quickly went to 100% even though I could see in Charles that bytes were still being transferred. I use the following method of NSURLSession:

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                     fromData:(NSData *)bodyData
                            completionHandler:(void (^)(NSData *data,
                                                        NSURLResponse *response,
                                                        NSError *error))completionHandler

并实施以下委托方法以接收进度事件:

and implement the following delegate method to receive progress events:

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend

实际上我正在使用AFNetworking 2.5.2,它使用这种方法。我的理论是这个委托方法报告从电话发送的字节而不是实际传输的字节。

Actually I'm using AFNetworking 2.5.2, which uses this method. My theory is that this delegate method reports on bytes sent from the phone and NOT actual bytes transferred.

在非常低的连接下发送300kb将立即发送5-6个包在等待收到它们的同时报告100%的进度。

Sending 300kb at a very low connection will send 5-6 packages immediately and report a progress of 100% while waiting for them to be received.

是否有可能获得已确认转移的实际字节数的进度事件?

Is it possible to get progress events on the actual number of bytes that have been confirmed transferred?

推荐答案

是的,这是可能的!

[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
     float prog = (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100);
     [self.progBar setProgress:prog];
     NSLog(@"%f%% Uploaded", (totalBytesWritten / (totalBytesExpectedToWrite * 1.0f) * 100));

     }];

这篇关于NSURLSession,上传任务 - 获取实际传输的字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆