Search code examples
iosfilebundlensdata

Create a file in application bundle


My application creates an NSData from a song from the iTunes library. I wan't to write this to a file in the bundle ( the file doesn't exists ). How do I create a file there?


Solution

  • stavash is right; you can't save to the bundle. To save to the documents directory, do something like this:

    NSString *documentsDir = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *pathForFile = [documentsDir stringByAppendingPathComponent:fileNameString];
    
    [songData writeToFile:pathForFile atomically:YES];
    

    And then to recover the contents of the file:

    NSData *songData = [[NSData alloc] initWithContentsOfFile:pathForFile];