Ibai
Ibai

Reputation: 568

Writing data into file

I'm trying to make a txt log file with the actions that happens in my app. I want to save some text whenever the app is connecting to the server o displaying new info.

Well, how do I write to a file? I've tried using the method writeToFile: but it's not working because fileExistsAtPath: is returning NO.

My code is:

NSString *file_path = @"mylog.txt"; 
NSString *log = @"Hello World!!\n"; 
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil]; 

Thanks!

PS: Oh, would it be readable through Organizer with the iPhone plugged in?

Upvotes: 0

Views: 312

Answers (2)

Rui Peres
Rui Peres

Reputation: 25927

Try this method I wrote:

+(NSString*)createPath:(NSString*)fileName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *localizedPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];

    //NSLog(@"%@",localizedPath);
    return localizedPath;
}

It will return you a path for your file. You only need to give it a name.

Upvotes: 1

Gotschi
Gotschi

Reputation: 3194

You should use the < App_Home >/Documents folder for storing Documents

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file_Path = [documentsDirectory stringByAppendingPathComponent:@"log.txt"];    
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];

But normally if you want to see and dump things while running the app, you could just use NSLog() which outputs it in the console.

Upvotes: 1

Related Questions