Adding string on existing txt file -iOS - ios

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);
}

Related

Store multiple json object in to a text file iOS

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];
}
}

How to create a .txt file programmatically on iOS

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.
Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.
NSError *error;
NSString *stringToWrite = #"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
And to retrieve the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
I hope this help's you
-(void)writeToTextFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = #"This is Demo";
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)ShowContentlist{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
[content release];
}

Error reading csv file on iOS device

I created an app to save as an csv file, app works fine in iOS simulator with both write and read. When i load the app to iOS device it doesn't data.
- (IBAction)saveInfo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:#"%#,%#,%#\n",
self.food.text,
self.movies.text,
self.channel.text];
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
//resultView.text = docPath;
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
resultView.text = filename;
if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
{
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filename];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
self.food.text = nil;
self.movies.text = nil;
self.channel.text =nil;
NSLog(#"Info saved");
}
- (IBAction)viewInfo:(id)sender {
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
NSString *fileContent=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
resultView.text = fileContent;
}
You are building the path incorrectly. Use:
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendinPathComponent:#"result.csv"];
The code you have results in a path like <path to app bundle>/Documentsresult.csv and on the device you can't write to the app bundle.
On Button action u can write below code maybe File will be displayed in my point of view its running correctly you should tray.....
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFile = [docsDir
stringByAppendingPathComponent: #"datafile.csv"];
NSLog(#"%#",dataFile);
NSData *data = [filemgr contentsAtPath:dataFile];
NSString *fooString=#"----------------\n Full File Data \n ---------------- \n " ;
fooString = [fooString stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ];
self.FileTextView.text=fooString;

Append string to txt-iOS

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);
}

How to append string in local resource txt file for iOS sdk

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];
}

Resources