我正在使用 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;
}