Error occurred with NSURLConnection via 3G

1k views Asked by At

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;
}
0

There are 0 answers