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

5

我收到了有关我的iOS应用在慢速连接上传图像失败的错误报告。尽管我的超时时间可能不够长,但还有另一个问题。

我发现即使在Charles中可以看到仍在传输字节,上传进度也快速达到了100%。 我使用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%的进度,同时等待接收它们。

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

1个回答

1

是的,这是可能的!

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

     }];

我假设 operation 是一个 AFHTTPRequestOperation。恐怕这与使用会话的上述方法存在相同的“缺陷”。 - Nicolai Dahl
如果您正确执行上传操作,那么就不应该出现任何问题。我已经使用相同的操作上传了30张图片,并按照答案中提到的方式跟踪了进度。请确保您正在使用“multipart”。 - Vizllx
你尝试过使用像 Charles 这样的代理应用程序来限制上传速度,例如 30 kpbs 吗?这就是在上面描述的问题中进度开始表现出奇怪行为的时候。 - Nicolai Dahl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接