我正在使用IOS sdk上传文件,在Wifi上工作正常,但有时候在大文件上使用3G时会出现以下错误
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)anError .....
“NSURLErrorDomain -1021请求正文流已耗尽”。
我知道我可以通过实现方法来覆盖这个问题:
- (NSInputStream*)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *) request
所以我做到了。但是当这个方法调用我遇到didFailWithError时出现下一个错误“操作无法完成。无法分配内存”。
如果我向方法needNewBodyStream添加一些延迟,则此错误消失。 有人可以解释一下这个延迟需要什么,我怎么能摆脱这个黑客?
这是我的代码:
- (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;
}