Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Log File in an iOS app

So in my app I have a bunch of data that I'd like to write to a log file, and then display it within a UITextView when I click a button. I know how to toggle the UITextView, but I have no idea how to create and update a log file (in the local filesystem). Thanks for any help.

like image 945
Julian Coltea Avatar asked Jun 15 '12 20:06

Julian Coltea


2 Answers

The basic idea is that you create the file, and append to it every time you log a new line. You can do it quite easily like this:

Writing to the file:

NSString *content = @"This is my log";

//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"];

//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
    [[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];

//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];

Reading:

//get file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"];

//read the whole file as a single string
NSString *content = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
like image 66
CrimsonDiego Avatar answered Oct 19 '22 12:10

CrimsonDiego


I thought was a class out there to do this automatically as after no luck created my own.

NSLogger is a lightweight class for iOS versions 3.0 and above. It allows developers to easily log different 'events' over time which are locally stored as a .txt file.

https://github.com/northernspark/NSLogger

like image 22
Joe Barbour Avatar answered Oct 19 '22 13:10

Joe Barbour