As shown code below, I am attempting to save all string comes. However, even though it displays txt created but there is no txt created. refer this question Adding string on existing txt file -iOS
-(void)saveData:(NSString*)data
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *fileName=[NSString stringWithFormat:#"%#/%d.txt",documentDirectory,1];
NSString *content=data;
NSFileHandle *fileHandler= [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandler seekToEndOfFile];
[fileHandler writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandler closeFile];
NSLog(#"%#",fileName);
}
Related
When there is no internet connection on device, i am storing the json in to a text file. But the problem is, if i do again it is getting replaced. Here is what i am doing for store into a text file. How to store multiple json object in a text file.When i get connection i need to post json to server.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"File.json"];
[jsonString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Please advice.
That's not so straight forward as concatenating multiple JSON files does not result in a valid JSON file. To do this properly requires you to read and parse the existing JSON file, which will give you an NSArray or NSDictionary top-level object, then append the data from the new JSON file and write the whole thing out.
That is inefficient as you are processing old data.
Therefore I would suggest you write new data to a new file, using the current date/time for the filename, and when it's time to upload, read each of the files and upload them individually, one-at-a-time. Then delete each file as it's uploaded.
Use below method to append text to file
-(void) writeToLogFile:(NSString*)content{
content = [NSString stringWithFormat:#"%#\n",content];
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"File.json"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
if (fileHandle){
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
else{
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
}
I was having trouble to read a txt file in my app. I was able to write the file but i could not read the file i've just written. So i searched for some tutorials and decided to create a separated sample. But it still not working.
Here is the code i am using :
- (IBAction)gerarArquivo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:#"%#,%#\n",#"teste1",#"teste2"];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *surveys = [docPath stringByAppendingPathComponent:#"results.csv"];
if (![[NSFileManager defaultManager] fileExistsAtPath:surveys]) {
[[NSFileManager defaultManager] createFileAtPath:surveys contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:surveys];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
NSLog(#"Foi");
}
- (IBAction)recuperarArquivo:(id)sender {
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *surveys = [docPath stringByAppendingPathComponent:#"results.csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:#"/results.csv"])
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:surveys];
NSString *surveyResults = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding];
[fileHandle closeFile];
NSLog(surveyResults);
}
}
Your reading code has an if statement containing:
[[NSFileManager defaultManager] fileExistsAtPath:#"/results.csv"]
which is unlikely to work due to the supplied path (should be fileExistsAtPath:surveys), and if that doesn't work then you won't ever try to read the file contents.
As shown code below, It is outputting several individual .txt files. However, I am looking in a way to save everything into one txt file. How could I append new string at the end of saved txt file?
-(void)saveData:(NSString *)data
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *fileName=[NSString stringWithFormat:#"%#/%d.txt",documentDirectory,fileInt];
NSString *content=data;
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSLog(#"%#",fileName);
fileInt++;
}
Ok, I think I got it.
-(void)saveData:(NSString*)data
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *fileName=[NSString stringWithFormat:#"%#/%d.txt",documentDirectory,1];
NSString *content=data;
NSFileHandle *fileHandler= [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandler seekToEndOfFile];
[fileHandler writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandler closeFile];
NSLog(#"%#",fileName);
}
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.
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];
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
I have been trying to append strings to a local resource file but I am having trouble finding a solution. I am trying to create a log file for all the function call in my application so if it crashes I can see which function it stopped on.
I have created a log.rtf file, but am not able to write in this file. Can someone please help me append a string to this file without having to overwrite the entire thing?
I have use following code for the above problem.
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *logPath = [[NSString alloc] initWithFormat:#"%#",[documentsDir stringByAppendingPathComponent:#"log.rtf"]];
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logPath];
[fileHandler seekToEndOfFile];
[fileHandler writeData:[text dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandler closeFile];
This way you can do this..
+ (void)WriteLogWithString:(NSString *)log
{
if(log != nil){
NSString *locationFilePath = [self getLogFilePath];//access the path of file
FILE *fp = fopen([locationFilePath UTF8String], "a");
fprintf(fp,"%s\n", [log UTF8String]);
fclose(fp);
}
}
- (void)log:(NSString *)message {
NSMutableString *string = [[NSMutableString alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]];
if (!string) string = [[NSMutableString alloc] init];
[string appendFormat:#"%#\r\n", message];
[string writeToFile:[NSString stringWithFormat:#"%#/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] atomically:YES encoding:NSUTF8StringEncoding error:nil];
}