5

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?

Nicolai Dahl
  • 249
  • 3
  • 9

1 Answers1

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

     }];
Vizllx
  • 8,843
  • 1
  • 36
  • 77
  • I assume `operation` is an `AFHTTPRequestOperation`. This has the same "defect" as the above approach using a session, I'm afraid. – Nicolai Dahl May 29 '15 at 07:54
  • If you are doing the upload operation in correct way, then it should not create any problem. I have uploaded 30 images using the same operation also tracked the progress as mentioned in the answer. Make sure you are using "multipart". – Vizllx May 29 '15 at 08:01
  • Have you tried using a proxy application like Charles to throttle the upload speed to e.g. 30 kpbs? This is when the progress starts to act weirdly as described in the issue above – Nicolai Dahl May 29 '15 at 13:58