Search code examples
iphoneobjective-ciosnsstringnslog

Objective-C: Create text file on device and easily retrieve the file


I am wanting to write my own logs to a text file on my iPhone. I wrote up a quick method that writes a string to a file. Right now it saves it into the Documents directory, which, if on the device is going to be a pain to get off, since I can't just browse to it. Is there a better way to quickly get this file off the device after I have written to it?

/**
 * Logs a string to file
 *
 * @version $Revision: 0.1
 */
+ (void)logWithString:(NSString *)string {

    // Create the file
    NSError *error;

    // Directory
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"log.txt"];

    // Get the file contents
    NSData *localData = [NSData dataWithContentsOfFile:filePath];
    if (localData) {
        NSString *logString = [[NSString alloc] initWithData:localData encoding:NSUTF8StringEncoding];
        string = [logString stringByAppendingFormat:@"%@\n", string];
        [logString release];
    }

    // Write to the file
    [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

}//end

Solution

  • Add Application supports iTunes file sharing to your application target's build info in Xcode:

    enter image description here

    Then, you can easily browse, retrieve and delete any files created by the app from iTunes, right under Devices > Your device > Apps > File Sharing:

    enter image description here