Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSession, upload task - Get actual bytes transferred

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?

like image 460
Nicolai Dahl Avatar asked Nov 09 '22 12:11

Nicolai Dahl


1 Answers

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

     }];
like image 178
Vizllx Avatar answered Nov 15 '22 05:11

Vizllx