NSURLSession, upload task - Get actual bytes transferred

心不动则不痛 提交于 2019-12-06 03:46:03

问题


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.

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

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.

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?


回答1:


Yes this is possible!

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

     }];


来源:https://stackoverflow.com/questions/30522793/nsurlsession-upload-task-get-actual-bytes-transferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!