Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging to a file on the iPhone

What would be the best way to write log statements to a file or database in an iPhone application?

Ideally, NSLog() output could be redirected to a file using freopen(), but I've seen several reports that it doesn't work. Does anyone have this going already or have any ideas how this might best be done?

Thanks!

like image 914
Mike McMaster Avatar asked Oct 14 '08 18:10

Mike McMaster


People also ask

What is a log file on iPhone?

A log file is simply a file that records events that happen while iOS or apps run on your iOS device.

Is there an activity log on iPhone?

Go to Settings > Screen Time. Tap See All Activity, then do any of the following: Tap Week to see a summary of your weekly use. Tap Day to see a summary of your daily use.

How do I log into my iPhone from my Mac?

In the Console app on your Mac, in the Devices list on the left, select the device you want to view log messages for (such as your Mac, iPhone, iPad, Apple Watch, or Apple TV). If you don't see the Devices list, click the Sidebar button in the Favorites bar. In the window to the right, click “Start streaming.”


1 Answers

If you want to use Cocoa, NSString and NSData have methods for reading/writing to file and NSFileManager gives you file operations. Here's an example (should work on iPhone):

NSData *dataToWrite = [[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"];

// Write the file
[dataToWrite writeToFile:path atomically:YES];

// Read the file
NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];  

// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager fileExistsAtPath:path]; // Returns a BOOL    

// Remove the file
[fileManager removeItemAtPath:path error:NULL];

// Cleanup
[stringFromFile release];
[fileManager release];
like image 94
Martin Gordon Avatar answered Sep 25 '22 02:09

Martin Gordon