Error while writing data to a file in iphone - iphone

in my application, i have placed an empty
myFile.txt
when i have internet connection , i get json data from internet and save the json string in it with following code
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
[myString writeToFile:filePath automatically:YES encoding:NSUTF... error:nil];
//now while retrieving it when no internet connection
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF.. error:nil];
now myString returns with #""... why i am not been able to write data?
Best Regards

Whatever you want to do is not possible (or at least strongly discouraged) to update files in the app bundle.
If you’re downloading files and want to store them on the device you should use the Documents directory. You can get the path to this directory with:
- (NSString *)getDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}

First check weather the contents are getting written to file. You can view the file in xcode.
What i suggest is when you run the app create this empty file. Then you can Read and write to that file easily.
Try Using Below code:
NSError* error = nil;
NSString* jsonFileName = [NSString stringWithFormat:#"myfile"];
NSString* jsonPath = [[NSBundle mainBundle] pathForResource:jsonFileName
ofType:#"txt"];
NSString* jsonString = [NSString stringWithContentsOfFile:jsonPath
encoding:NSUTF8StringEncoding error:&error];
Documents directory:
Write to file
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:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
Display content:
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:#"%#/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];

Related

Saving Data from iphone app to text file in iPhone app

I want to save my application data in text file in documents folder
I am using following way to store but it store single string i want that my data is in array how may store all the contents of array in text files
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString*yourString=#"This is working fine";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
NSString *stringWithoutSpaces = [yourString stringByReplacingOccurrencesOfString:#" " withString:#""];
[stringWithoutSpaces writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
My Array is like Following
DataController *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];
cell.resturantLocationLabel.text=coffeeObj.resturantLocation;
cell.foodQualityRatingLabel.text=coffeeObj.foodQualityRating;
cell.foodPresentationRatingLabel.text=coffeeObj.foodPresentationRating;
cell.waiterRatingLabel.text=coffeeObj.waiterRating;
cell.ambienceRatingLabel.text=coffeeObj.ambienceRating;
cell.overallRatingLabel.text=coffeeObj.overallRating;
cell.commentsLabel.text=coffeeObj.comments;
cell.emailAddressLabel.text=coffeeObj.emailAddress;
cell.addtoMailingListLabel.text=coffeeObj.addtoMailingList;
NSString*test=coffeeObj.comments;
add your complete array data in NSMutableString and then store in text file.
// Here you set your text.
NSString *yourAppendingText = #"yourAppendingText";
// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:#"file.txt"];
// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one if it is
if(textFromFile){
NSLog(#"appending");
NSString *textToFile = [textFromFile stringByAppendingString:[NSString stringWithFormat:#" %#",yourAppendingText]];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
else{
NSLog(#"not appending");
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

I'm having trouble cacheing the path of an existing file

Here is my code, I was using a QLPreviewController for display a detail view with a pdf file which I download and stock at the beginning of the program.
It throw a exception with telling the path was null.
-(id<QLPreviewItem>)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)index{
NSString *name=[selectedItem.source lastPathComponent];
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:name] ){
NSLog(#"%# exsit! ",name); //In!!!
}
name = [name stringByDeletingPathExtension];
NSLog(#"name for QL: %#",name); //Name ok!!!
NSString *path = [[NSBundle mainBundle]pathForResource:name ofType:#"pdf"];
NSLog(#"path: %#",path); //Path: null !!!
return [NSURL fileURLWithPath:path]; //error!!
}
Files don't download to [NSBundle mainBundle]. Try changing that line to
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathString = [documentsDirectory stringByAppendingPathComponent:fileName];`
rather than reading from [NSBundle mainBundle]. You can't download files to mainBundle. It's read only.

How to read a file in iPhone?

I am trying to read a .txt file from my documents directory in the form of NSString. Any idea how to read the file into NSString?
Thank you...
Use NSString's stringWithContentsOfFile: method.
NSString *fileContents = [NSString stringWithContentsOfFile:#"some/file.txt"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
}
//Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];
This worked for me
Anyway, thank you all..
Hopefully this is what you're after :
NSString *myString = [[NSString alloc] initWithContentsOfFile:#"pathToFile"];
I usually have it looking in the Applications Document directory.
Hope this helps...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileContents=[documentsDirectory stringByAppendingPathComponent:#"file.txt"];
hAPPY cODING...
I think this is the best way to read .txt file from DocumentDirectory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"txtFile.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
I hope this will work for you!!

Read and write file in iPhone

How to make file read/write operation on iPhone?which is the path i need to specify to save the file? how can i get the current working directory in iPhone?
Thank You
Write to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
[data writeToFile:myFile atomically:YES];
Read a file:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"txt"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
// do something useful
}