NSURLSession,上传任务 – 获取实际的字节传输

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

我发现上传进度很快达到了100%,尽pipe我可以在Charles看到字节仍在传输。 我使用NSURLSession的以下方法:

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

并实现下面的委托方法来接收进度事件:

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

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

以非常低的连接发送300kb的数据包,将立即发送5-6个包,并在等待接收时报告100%的进度。

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

是的,这是可能的!

 [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)); }];