gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:13:21 25 4
gpt4 key购买 nike

我有一个循环获取一堆文件的 URL(10 个小的 txt 文件和 1 个大约 700KB 的大图像文件)并运行“getFile”为每个文件创建一个 NSUrlConnection。

当应用程序到达 [file writeData:data] 之前的 [fileeekToEndOfFile] 时,它会崩溃:

*** 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,而不是委托(delegate)的文件属性。而且我认为您不需要 [file seekToEndOfFile];

编辑:示例子类 NSURLConnection

@interface FileURLConnection: NSURLConnection

@property (nonatomic, strong) NSFileHandle *file;

@end

关于ios - 下载大文件时应用程序崩溃 - NSFileHandle seekToEndOfFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21986815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com