问题
I have a loop that gets the URLs of a bunch of files (10 small txt files and 1 large image file around 700KB) and runs 'getFile' which creates an NSUrlConnection for each one.
When the app gets to [file seekToEndOfFile] just before [file writeData:data] it crashes with:
*** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle seekToEndOfFile]: No such process'
*** First throw call stack:
The strange thing is that if I step through the code (i.e. slowly allowing each connection to go and come back) then all files are downloaded fine. If I just let the app do its thing it crashes.
Here is code for the connections:
-(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);
}
Does my app have a problem keeping reference to the outgoing connections? I had assumed that NSURLConnections, by default, were asynchronous and you would not need to 'keep track' of them?
EDIT I have subclassed NSURLConnection and instantiated as below:
-(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:
I think you are downloading several files simultaneously with one delegate. Try subclass NSURLConnection
connection and add in it proterty file
, instead delegate's file property. And I think you don't need [file seekToEndOfFile];
EDIT: example subclassed NSURLConnection
@interface FileURLConnection: NSURLConnection
@property (nonatomic, strong) NSFileHandle *file;
@end
来源:https://stackoverflow.com/questions/21986815/app-crashing-when-downloading-a-large-file-nsfilehandle-seektoendoffile