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

2019-10-29 21:11发布

我有一个循环,得到一堆文件(10个小txt文件,并围绕700KB 1个大的图像文件),并运行“的GetFile”这对于每一个创建一个NSURLConnection的的网址。

当应用程序获取到[文件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];
}

Answer 1:

我想你同时下载多个文件与一个代表。 尝试子NSURLConnection连接,并在其中加入性态file ,而不是委托的文件属性。 我认为你不需要[file seekToEndOfFile];

编辑:例如子类NSURLConnection的

@interface FileURLConnection: NSURLConnection

@property (nonatomic, strong) NSFileHandle *file;

@end


文章来源: App crashing when downloading a large file - NSFileHandle seekToEndOfFile