Create and save NSString data in to a file - iphone

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

Related

Error while writing data to a file in 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];

can't creating plist file in document folder

I have write code like this in Viewdidload method. But it don't create file .plist.
I don't know whether code is wi8 or wrong. And where i have to write?
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data1.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( ![fileManager fileExistsAtPath:path] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"data1" ofType:#"plist"];
}
You have just created a path to it, you should try loading it into a NSDictionary.
NSDictionary* mydictionary = [ NSDictionary dictionaryWithContentsOfFile: pathToSettingsInBundle];
Inside your if block add a second line
[fileManager copyItemAtPath:pathToSettingsInBundle toPath:path error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
plistpath = [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:#"Product.plist"]];
And then
[array writeToFile:path atomically:YES];
[Whatever [Array or Dictionary] you want to Write in Plist]
If it is still not creating the plist then check whether your array or dictionary must be empty.

string is not being written in file - iPhone

I am using the following code in iPhone to write a string into the file that is stored in my iPhone Project Resource Folder. When i try to read its reading the data successfully but when i try to write its not writing the file although its aloso not giving me any error.
this is my code:
NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
[myString writeToFile:path atomically:YES];
Please can anybody guide.
- (void) testStringReadWrite {
NSString *myString = #"abcd efgh";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
CFShow(path);
NSError *error = nil;
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#",error);
}
NSString *readString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", error);
} else {
CFShow(readString);
}
}
The writeToFile:atomically: has been depredecated in iOS 2.0. Use writeToFile:atomically:encoding:error: instead. You should check the content of the string, for example by NSLog() function. Inappropriate initialization can cause a failure.
NSLog(#"%#", myString);
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Just my two cents, coming from OS X, I am used to calling writeToURL() instead of writeToFile(). Turns out, writeToFile() is the one that worked for iOS.

how to append tags in xml in iphone?

i am new developer in iphone application. i would like write a content in xml file for that, i have created xml file and write tags with element, attribute and value with some data in that xml as follows.
-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName NodeName:(NSString *)Node{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *fileExtension = [NSString stringWithFormat:#"%#%#",fileName,#".xml"];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists) {
NSError *error = nil;
NSString *docStr;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(#"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
XMLString = [[NSMutableString alloc]initWithString:docStr];
[self XMLString];
NSLog(#"data%#",XMLString);
}
}
// [XMLString insertString:data atIndex:index];
[XMLString appendFormat:#"<%#>%#</%#> \n",Node,data,Node];
BOOL success = [XMLString writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
else {
NSLog(#"File write is successful");
}
}
}
i want add new tag with new elements,new attributes,etc.,if i enter element at the place of tag it is modifying with previous tag .
here how can i append the new tag to previous appended tags
please any body could help me
Thanks in advance
As a suggestion, you can use APXML to create XML documents it is very simple and easy to use. This post can guide you further.

iphone, write csv file in sandbox

i must write (at start of app) and delete is content (at the end of app) a csv in my sandbox file with a stream of data.
For your experience, what's the best way to do this?
edit:
i'm trying with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename =#"test.csv";
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
[[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
NSString *data = [NSString stringWithFormat:#"%#,%#\n", latitudine.text, longitudine.text];
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
it work but.... every time writedata is call i got only one row, no append. i want to collect all values of my two textlabel.
Where my mistake?
edit2:
yessss, find the solution with this code:
first i've create this one:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"myfile.csv"];
}
and in my viewDidLoad i check and if does not exist, create my file
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
and in one of my method i add the code for retrieve data and append to my file:
NSString *data = [NSString stringWithFormat:#"%#,%# ", latitudine.text, longitudine.text];
//create my data to append
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
//write data to with the right encoding
Hope this helps!
If you put it in NSTemporaryDirectory(), I think it's supposed to be cleaned up on app exit — it's probably worth checking if this is the case.