Save NSLog into a Local File - ios

I'm learning how to develop for iPhone and i need to save de NSLog output on a local file on my machine to analyse the result in because I`ll run the application for a long time and I need to check after some hours running what was the output (and I want to save the output file on my machine from time to time, for example after every 30min).
How can I save the xcode output into a file?

Possibly not what you want, but I use this:
- (void)logIt:(NSString *)string {
// First send the string to NSLog
NSLog(#"%#", string);
// Setup date stuff
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-dd-MM"];
NSDate *date = [NSDate date];
// Paths - We're saving the data based on the day.
NSString *path = [NSString stringWithFormat:#"%#-logFile.txt", [formatter stringFromDate:date]];
NSString *writePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];
// We're going to want to append new data, so get the previous data.
NSString *fileContents = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:nil];
// Write it to the string
string = [NSString stringWithFormat:#"%#\n%# - %#", fileContents, [formatter stringFromDate:date], string];
// Write to file stored at: "~/Library/Application\ Support/iPhone\ Simulator/*version*/Applications/*appGUID*/Documents/*date*-logFile.txt"
[string writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
This writes the data into a file on your device (a daily file). If you want it to reset after each session you can surely modify the code to do that.
And of course you'll have to change all your existing NSLog() calls to use [self logIt:] instead.
This also works on a real device (but the file location is different of course).

Related

How to read and store System Log messages in IOS using Objective-C

My intention is to read all the system log messages pertaining to my application(all those log messages present inside the system.log file), and store it in a log file within the app's Document folder.
I went through this code and used this answer.
Here is my code:
NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:[NSString stringWithFormat: #"dd-MM-yyyy-HHmmss"]];
NSString *logFileName = [[formatter stringFromDate:currentDate] stringByAppendingString:#".log"];
NSError *error;
NSMutableString *content = [[NSMutableString alloc] init];
aslmsg q, m;
int i;
const char *key, *val;
q = asl_new(ASL_TYPE_QUERY);
aslresponse r = asl_search(NULL, q);
while (NULL != (m = asl_next(r)))
{
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];
for (i = 0; (NULL != (key = asl_key(m, i))); i++)
{
NSString *keyString = [NSString stringWithUTF8String:(char *)key];
val = asl_get(m, key);
NSString *string = [NSString stringWithUTF8String:val];
[tmpDict setObject:string forKey:keyString];
}
[content appendString:[NSString stringWithFormat:#"%#",tmpDict]];
}
asl_release(r);
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:logFileName];
[[NSString stringWithString:content] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
This is just a part of code of my IOS app. I am running my app on the IOS Simulator.
The log files gets successfully created. It has some content which is predominantly JSON.
However, the file does not have those log messages which I outputting through NSLog, yet those log messages are present inside the System's log file.
I am quite new to IOS Development. As stated, my purpose to access the System's log files. So I want to capture each log message and save it into my personal directory.
I searched a lot on this Stackoverflow. However, I haven't found the exact thread which could help me on this. Can anyone guide me appropriately?
(I hope this question isn't duplicated.)
I guess you want them to check them later in case you find an error. Maybe you can try Bugfender (http://bugfender.com), it's a tool we have created to get the logs from our customers while developing apps.
With it, you are going to be able to get also all NSLog calls.
The answers you have checked are the right way to do it if you don't want to use Bugfender. In our case we are using the functions documented here

Best way to persist an array of images?

I'm looking for a way to persist images to an array (or similar) that can be accessed after the app has closed an relaunched -- sorting the images by date is also required. I'm currently able to store the the images to the app's NSDocumentDirectory with the following code:
-(NSString *)currentDateandTime
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMddyyyy_HHmmss"];
NSString *dateString = [dateFormat stringFromDate:today];
return dateString;
}
-(void)saveImageToDocuments
{
NSData *imageData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *date = [self currentDateandTime];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_image.png",date]];
}
This means I've got images where the date/time is in the filenames of the image. What is the best way to go about storing these images in an array or dictionary AND sorting them by date/time. Thanks for reading!
I would save the file names and dates in a plist file which is an array of dictionaries of format: #{ #"filename" : imageFileName, #"date": imageDate }.
When you load that plist into an NSArray, you can easily sort it by date by specifying your own comparison method. e.g:
NSArray *filenames = [[NSArray alloc] initWithContentsOfFile:filePath];
NSArray *sortedFilenames = [filenames sortedArrayUsingComparator:
^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2)
{
NSDate *date1 = dict1[#"date"];
NSDate *date2 = dict2[#"date"];
return [date1 compare:date2];
}
Store the image data and the dates in some dictionaries, then store those dictionaries in an array, then use NSKeyedArchiver to archive the array.
[NSKeyedArchiver archiveRootObject:imageDictionary toFile:#"imagesArray"];
Then when you want to retrieve it:
NSArray * retrievedImages = [NSKeyedUnarchiver unarchiveObjectWithFile:#"imagesArray"];
Then just compare the dates in the various dictionaries in the retrieved array.

How to save unique image name in document directory

In my ios app i am stuck on a task. I need to take pic from camera and save it on document directory.Problem is that i want save unique name of image.I was try to add current time with a name. but there are length problem to save image.Please suggest me how can i do that task.
Thanks
Given a proposed name like NString *name = #"Lake":
NSString *myUniqueName = [NSString stringWithFormat:#"%#-%u", name, (NSUInteger)([[NSDate date] timeIntervalSince1970]*10.0)];
EDIT: updated so that the only chance of a duplicate is the same original name, submitted within 100 ms of the first (virtually impossible in my opinion, if this is a concern use 100 instead of 10)
-(NSString*)getFilePathToSaveUnUpdatedImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
for (int i = 0 ; TRUE ; i++)
{
if(![[NSFileManager defaultManager]fileExistsAtPath:[NSString stringWithFormat:#"%#/UnUpdatedItems/Image%d.png", directory , i]])
return [NSString stringWithFormat:#"%#/UnUpdatedItems/Image%d.png", directory , i];
}
}
Try like this just formate the date and save the image
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *now = [NSDate date];
NSString *theDate = [dateFormat stringFromDate:now];
[data writeToFile:[NSString stringWithFormat:#"%#.png",theDate] atomically:YES];
use this line of code to give name.
[NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle]]
This works for me for same problem.
-(NSString*)getImagePathName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
for (int i = 0 ; TRUE ; i++)
{
if(![[NSFileManager defaultManager]fileExistsAtPath:[NSString stringWithFormat:#"%#/Image%d.png", directory , i]])
return [NSString stringWithFormat:#"%#/Image%d.png", directory , i];
}
}

Parsing NSString

I am currently at the point to where I want to create a simple text file, read it into my application, convert the string "0700 1300" to an NSDate format to be read into my native calendar.
I am pretty new to objective-c but I am trying to read in both 0700 into the start time of an event and 1300 into the end time of an event. I just cant get the 1300. Mainly I want to store the first WORD "0700" and the second WORD "1300".
EDIT:
If possible please include code that converts the string "0700 1400" to a string will later be the time interval of
EKEvent *myEvent;
This is the code I use to store the data within the text file I'm downloading from the web.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self.myDataArray addObject:dataString];
myDataArray is a mutable array which I initiated earlier in viewDidLoad of my current view controller.
This is a small snippet of the textfile im reading in.
Sunday
0 1200
Sunday
2100 2400
Monday
0 600
I was able to parse my text file but now the issue of converting the string that contains the start date and end date to an NSDATE.
I am not looping through the entire file yet, just one line within the specific file, i'll loop through the entire file once I can format ONE line at least.
I currently have converted 0 and 1200 to 2013-06-08 00:00:00 +0000 and 2013-06-08 12:00:00 +0000 by appending and inserting.
Heres the code I used.
NSData *data = [[NSData alloc] initWithData:downloadFile.receivedData];
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSArray *components = [dataString componentsSeparatedByString:#"\n"];
NSString *anotherString = [NSString stringWithFormat:components[1]];
NSArray *times = [anotherString componentsSeparatedByString:#" "];
NSMutableString *startDate = [[NSMutableString alloc] initWithString:times[0]];
NSMutableString *endDate = [[NSMutableString alloc] initWithString:times[1]];
for (int i = startDate.length; i < 4; i++)
[startDate appendString:#"0"];
[startDate appendString:#":00 +0000"];
for (int i = endDate.length; i < 4; i++)
[endDate appendString:#"0"];
[endDate appendString:#":00 +0000"];
[startDate insertString:#":" atIndex:2];
[endDate insertString:#":" atIndex:2];
[startDate insertString:#"2013-06-08 " atIndex:0];
[endDate insertString:#"2013-06-08 " atIndex:0];
I realized that when adding events, I don't need to know the end time just the time interval. So i plan on taking the start TIME and comparing it to the end TIME and find the time interval that way.
I understand the DATE i give my string is of a constant date but that isn't the issue at the moment, I'll fix that later. But for now I would like to convert the NSString *startDate I created and stored the date/time string in to an NSDate *startDate so that I can use it as the start dat of an EKEvent.
Thank you guys.

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

Resources