7

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
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412
  • Sidenote—if the log file gets to be any bigger than about 500KB or so, this will become really inefficient. Consider only writing changes (using other API) – FeifanZ Nov 01 '11 at 00:37

3 Answers3

10

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

Lukman
  • 18,462
  • 6
  • 56
  • 66
0

You may have to capture what number of logs you have created so far and create a new name for each log biased on that.

So you might save your last made logs name as a string in NSUserDefaults and get the number off the end of that and add one onto that captured int ready for the next name.

So if you have @"Log4" you can get the 4 out of that and make it 5 so that the next log is named "Log5"

Just my 2 cents :P

Necro
  • 333
  • 5
  • 18
0

With regard to the 'How to get the file' part of the question

iExplorer, previously iPhone Explorer allows you to view your apps, including their documents folder without jailbreaking your devices.

In my experience (albeit of an older version), getting the files from the phone can be a little temporamental (i.e. I drag a file onto my desktop and although it creates the file, it doesn't write any of the data), you can get the files from your device.

James Webster
  • 31,873
  • 11
  • 70
  • 114