Search code examples
objective-ciosnsdatansurlnsfilemanager

copyItemAtPath, moveItemAtPath, and createFileAtPath all seem to create a file that's unreadable


So I'm trying to figure out why I can't make a copy of my file that's readable. I've tried moveItemAtPath, copyItemAtPath, and createFileAtPath. Each time, reading the data from the original path works fine but reading it from the new file path results in a 0 byte nil NSdata object.

NSData* tempData = [NSData dataWithContentsOfURL:tempSoundFile]; // reads just fine

NSError* error;
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString* docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* uniqueFileName = [[NSString stringWithFormat:@"%@-%@", description.text, [NSDate date]] MD5];
NSString* newAudioFile = [NSString stringWithFormat:@"%@/%@.caf", docDir, uniqueFileName];

if (LOG) { NSLog(@"Copying %@ to %@", tempSoundFile.path, newAudioFile); }

// Have tried either or both as well as moveItemAtPath with the same result
[fileMgr createFileAtPath:newAudioFile contents:tempData attributes:nil];
//[fileMgr copyItemAtPath:tempSoundFile.path toPath:newAudioFile error:&error];

NSData* audioAfter = [NSData dataWithContentsOfURL:[NSURL URLWithString:newAudioFile]]; // nil data

Log Output:

Copying /var/mobile/Applications/19531C7F-F408-45B9-B417-09315BB15B49/Documents/8554temp.caf to /var/mobile/Applications/19531C7F-F408-45B9-B417-09315BB15B49/Documents/933becb02783c8f9c715acbdca0e15ed.caf

Does anyone have any suggestions as to what I'm doing wrong? Thanks


Solution

  • Change your last line to:

    SData* audioAfter = [NSData dataWithContentsOfFile:newAudioFile]; // NOT nil
    

    Because path url with NSURL expect a file:// at the beginning.