3

I am using the IOS sdk to upload file, works fine over Wifi, but over 3G sometimes on large files the following error is caught in

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)anError ..... 

"NSURLErrorDomain -1021 request body stream exhausted".

I know i can override this problem by implementing the method:

- (NSInputStream*)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *) request 

so i did it. But when this method called i caught in didFailWithError next error "The operation couldn’t be completed. Cannot allocate memory".

This error disappears if I add to method needNewBodyStream some delay. Can somebody explain me for what need this delay, and how can i get rid of this hack?

here is my code:

- (void) startUpload    
{    
   NSInputStream* fileStream = [[NSInputStream alloc] initWithFileAtPath: sourcePath];

   [self.request setHTTPMethod:@"PUT"];

   [self.request setValue:[NSString stringWithFormat: @"%lu", fileSize] forHTTPHeaderField: @"Content-Length"];

   [self.request setHTTPBodyStream: fileStream];

   NSURLConnection* newConnection = [[NSURLConnection alloc] initWithRequest: self.request delegate: self startImmediately: YES];

   self.connection = newConnection;

   [newConnection release];
   [fileStream release];
}

#pragma mark NSURLConnectionDelegate

- (NSInputStream *) connection: (NSURLConnection *) aConnection needNewBodyStream: (NSURLRequest *) request
{
   [NSThread sleepForTimeInterval: 2];

   NSInputStream* fileStream = [NSInputStream inputStreamWithFileAtPath: sourcePath];

   if (fileStream == nil)
   {
       NSLog(@"NSURLConnection was asked to retransmit a new body stream for a request. Returning nil will cancel the connection.");
   }

   return fileStream;
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Konstantin
  • 31
  • 3
  • Please reassure me the sleep is purely while debugging – Mike Abdullah May 30 '12 at 17:06
  • How are you calculating fileSize? Sure that your Content-Length header is correct? – Mike Abdullah May 30 '12 at 17:07
  • i'm sorry, i didn't add to post. fileSize is calculating in method - (void) startUpload `NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath: sourcePath error: &error]; unsigned long long fileSize = [fileAttribs fileSize];` I'm debugging on device IPad2 with 3G. – Konstantin May 31 '12 at 08:08

0 Answers0