Troubles reading a txt file - ios

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.

Related

Writing and retrieving files from NSDocumentDirectory iOS

I want to download a file(pdf, doc, docx etc) in NSFileManager from some specific URL. Later on when user taps on same link I want to retrieve the file from NSFileManager. Here is the code I've done:
- (void)checkIfFileExist {
NSString *path1;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
path1 = [path1 stringByAppendingPathComponent:#"sample.pdf"];
NSLog(#"The read path is %#", path1);
if ([[NSFileManager defaultManager] fileExistsAtPath:path1])
{
//File exists
NSData *file1 = [[NSData alloc] initWithContentsOfFile:path1];
if (file1)
{
}
}
else
{
NSURL *url = [NSURL URLWithString:#"http://fzs.sve-mo.ba/sites/default/files/dokumenti-vijesti/sample.pdf"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
path = [path stringByAppendingPathComponent:#"sample.pdf"];
NSLog(#"The written path is %#", path);
[[NSFileManager defaultManager] createFileAtPath:path
contents:urlData
attributes:nil];
}
}
Now here every time I'm trying to fetch the file from file manager the condition that file exists always returning me FALSE. The paths where I'm writing and reading the file are same as I've checked them on console. Any mistake that I've done?
Add this
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];}
after
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
in your else part and replace
[[NSFileManager defaultManager] createFileAtPath:path contents:urlData attributes:nil];` with `[urlData writeToFile:path atomically:YES];

Saving CSV file to documents directory folder

I am writing a registration app that is supposed to save a CSV file in the documents directory folder. I would like to look at the output and see what happens when I open the CSV file in excel. I navigated to the documents directory folder by finding out where it should be saved using this code snippet:
NSLog(#"Info Saved");
NSLog(#"Documents Directory: %#", [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject]);
Here is my code for saving the information put into the 11 text fields in the registration form:
- (IBAction)saveFormButton:(id)sender {
// saves text field data in comma separated CSV file format
NSString *formData = [NSString stringWithFormat:#"%#,%#,%#,%#,%#,%#,%#,%#,%#,%#,%#\n",
self.nameTextfield.text, self.emailTextfield.text,
self.phoneTextfield.text, self.termTextfield.text,
self.schoolTextfield.text, self.graduationTextfield.text,
self.gpaTextfield.text, self.degreeTextfield.text,
self.interestTextfield.text, self.groupTextfield.text,
self.appliedTextfield.text];
// get document directory path
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0];
// append results.csv onto doc path
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
// creates folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
Should I be seeing a file in that specific folder I have navigated to?
Thank you for your help,
Change this line:
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
to:
NSString *event = [documentDirectoryPath stringByAppendingPathComponent:#"results.csv"];
This makes sure that the path is correctly formatted. Also, you seem to be checking to see if "documentDirectoryPath" exists before creating the file rather than the filename itself. Change:
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
to:
if (![[NSFileManager defaultManager] fileExistsAtPath:event]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
Here is a more elegant way with less code
// Content of file
NSString* str= #"str,hey,so,good";
// Writing
NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:#"file.csv"];
[str writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
// Reading
NSString *string = [[NSString alloc] initWithContentsOfFile:root encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",string);
The result:
2015-07-15 15:52:56.267 ObjC[2927:15828] str,hey,so,good

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;

Create a file to an application document folder

I want to create a file in my application document folder and i have to store some content. That content takes from my localhost file. So i write a below code. But this code didn't create a file in my application document folder.
- (void) createFile
{
NSString *strPath = [NSString stringWithFormat:#"http://192.168.5.117/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"File Exists");
}
else
{
NSLog(#"File not exists");
}
NSString *content = [NSString stringWithFormat:#"%#",data];
[content writeToFile:strLastpath atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
}
While build for running i got this.
2013-10-11 11:36:38.833 SampleFileCreation[1321:c07] Path : http://192.168.5.117/~mac/banana.obj
File Name : Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] Database Path : /Users/mac/Library/Application Support/iPhone Simulator/6.1/Applications/4FA749DF-D12D-4956-AF76-140D2F981F17/Documents/Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] File not exists
You can also try this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileName = #"yourFileName";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/fileName"];
NSDate *data = [NSData dataWithContentsOfURL:YourUrl]; // get date form url
[data writeToFile:dataPath atomically:YES]; // save data in file
I found the answer. File created successfully.
- (void) createFile {
NSString *strPath = [NSString stringWithFormat:#"http://-.-.-.-/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
docsDir=[docsDir stringByAppendingString:#"/Object File"];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSError *theError = nil;
NSFileManager *filemgr = [NSFileManager defaultManager];
**//I added this line**
[filemgr createDirectoryAtPath:docsDir
withIntermediateDirectories:YES
attributes:nil
error:&theError];
**//Changed this line**
[data writeToFile:[docsDir stringByAppendingPathComponent:strLastpath]
options:NSDataWritingAtomic
error:&theError];
if ([filemgr fileExistsAtPath:[docsDir stringByAppendingPathComponent:strLastpath]]){
NSLog(#"File Exists");
} else {
NSLog(#"File not exists");
NSLog(#"Tell Me error %#",[theError localizedDescription]);
}
}

Adding string on existing txt file -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);
}

Resources