The problem:
I want to create a temporary file that holds RAW data from the asset I've read through ALAssetLibrary
. But as soon as I try to create a file via NSFileManager
´s [createFileAtPath:contents:attributes:]
the application stops and throws a EXC_BAD_ACCESS
. Well, that error often means that I have a broken or faulty pointer but there is really nothing in my code that is set to nil except for the fileHandle IVAR.
I managed to run the code a couple of times successfully but after that it crashes every single time it comes to create the file under iOS7+. iOS versions below that seems to be able to create and write to the file, but as soon as I try to access it in any way, the same error comes up.
- Just to clarify: There are NO files present in the "tmp" directory.
- Below, the full path to the temp file is:
/private/var/mobile/Applications/83BFD709-3587-404D-97E7-BEAAA2860283/tmp/temp.tmp
The error prone code:
- (NSString *)applicationTempDirectory
{
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
//NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString* basePath = NSTemporaryDirectory();
return basePath;
}
Below follows the part that cause the crash.
.... <NEW METHOD>
NSUInteger chunkSize = 1000 * 1024; //1MB chunks
ALAssetRepresentation* rep = [asset_ defaultRepresentation];
uint8_t chunkbuffer[chunkSize];
long long length = [rep size];
// Copy file
NSString* tempFile = [NSString stringWithFormat:@"%@/temp.tmp", [self applicationTempDirectory]];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath: tempFile];
if(!fileHandle) {
NSLog(@"File path_: %@", tempFile);
[fileMgr createFileAtPath:tempFile contents:nil attributes:nil]; //<--- Here it throws the exception
fileHandle = [NSFileHandle fileHandleForWritingAtPath:tempFile];
}
NSUInteger offset = 0;
do {
NSUInteger bytesCopied = [rep getBytes:chunkbuffer fromOffset:offset length:sizeof(chunkbuffer) error:nil];
offset += bytesCopied;
NSData *data = [[NSData alloc] initWithBytes:chunkbuffer length:bytesCopied];
[fileHandle writeData:data];
data=nil;
} while (offset < length);
[fileHandle closeFile];
fileHandle = nil;
.... <CONTINUES ON>
The question:
Does anyone have any clue to why this seemingly easy task is not working as expected? I have tried literally everything except to set any attributes to the [createFileAtPath:contents:attributes:]
. I've searched the web for everything, but no one seems to have the same problem as i do. Some here on SO are close, but after trying the supplied solutions, it didn't work...