Search code examples
xcodeios5testingios-simulator

Copy data file from Xcode to iPad sandbox


I created an app in Xcode and added a text file for the app to open and display.

How can i get this text file into the iPad sandbox documents directory for testing?


Solution

  • There are a few things you need to do:

    1. Create a path to your Documents directory
    2. Make sure your text file is in your app bundle (Drag/drop into Xcode should be fine)
    3. Copy that text file by name from the app bundle to the Documents directory

    Try this:

    // Documents path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    
    // Destination path
    NSString *fileInDocumentsPath = [documentsPath stringByAppendingPathComponent:@"name-of-your-file.txt"];
    
    // Origin path
    NSString *fileInBundlePath = [[NSBundle mainBundle] pathForResource:@"name-of-your-file" ofType:@"txt"];
    
    // File manager for copying
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager copyItemAtPath:fileInBundlePath toPath:fileInDocumentsPath error:&error];