下载大文件时应用程序崩溃 - NSFileHandle seekToEndOfFile

时间:2014-02-24 11:46:03

标签: ios objective-c cocoa-touch nsurlconnection

我有一个循环,它获取一堆文件的URL(10个小txt文件和1个大图像文件大约700KB)并运行'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];
}

1 个答案:

答案 0 :(得分:1)

我认为您正在与一位代表同时下载多个文件。尝试子类NSURLConnection连接并添加proterty file,而不是委托的文件属性。我认为你不需要[file seekToEndOfFile];

编辑: 示例子类化NSURLConnection

@interface FileURLConnection: NSURLConnection

@property (nonatomic, strong) NSFileHandle *file;

@end