[英]iOS: NSFileHandle vs NSOutputStream for large file download
[英]App crashing when downloading a large file - NSFileHandle seekToEndOfFile
我有一个循环,它获取一堆文件(10个小txt文件和1个大图像文件,大约700KB)的URL,然后运行“ getFile”,为每个文件创建一个NSUrlConnection。
当应用程序在[file writeData:data]之前到达[file seekToEndOfFile]时,它崩溃并显示:
*** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle seekToEndOfFile]: No such process'
*** First throw call stack:
奇怪的是,如果我单步执行代码(即慢慢允许每个连接前进并返回),那么所有文件都可以正常下载。 如果我只是让应用执行其操作,则它会崩溃。
这是连接的代码:
-(void)getFile {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
[conn start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSString *fileName = [[response URL] lastPathComponent];
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[file seekToEndOfFile]; // crashing here
[file writeData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Connection is %@", connection);
[file closeFile];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"error - %@", error);
}
我的应用程序在保留对传出连接的引用方面是否有问题? 我假设默认情况下,NSURLConnections是异步的,您不需要“跟踪”它们吗?
编辑我有子类化NSURLConnection并实例化如下:
-(void)getFile {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
FileURLConnection *conn = [[FileURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES ];
conn.fileName = [fullURL lastPathComponent];
[conn start];
}
我认为您正在与一位代表同时下载多个文件。 尝试子类NSURLConnection
连接,并在其中添加属性file
,而不是委托的file属性。 而且我认为您不需要[file seekToEndOfFile];
编辑:子类NSURLConnection的示例
@interface FileURLConnection: NSURLConnection
@property (nonatomic, strong) NSFileHandle *file;
@end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.