write NSString to file - objective-c

I'm trying to write a string to a file and store that in the applicationSupport folder within my app. But my NSLog() statement doesn't log anything in the debugger. I have tried to go through it with the debugger, and i can see that the content is nil, so i'm guessing that's why it's not outputting anything, but i don't know why it's set to nil. Can anybody see my mistake?
NSString *document = [[[[[[[[description stringByAppendingString:#" "]stringByAppendingString:focus]stringByAppendingString:#" "]stringByAppendingString:level]stringByAppendingString:#" "]stringByAppendingString:equipment]stringByAppendingString:#" "]stringByAppendingString:waterDepth];
//NSLog(#"%#", document);
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
//filename
NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];
[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(#"%#", content);

filename is wrong. It should have the following format: "directory/file.extension". You can use the methods stringByAppendingPathComponent and stringByAppendingPathExtension to construct such a string.
NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:#"txt"]];
Also, as a side note, the first line should be rewritten using stringWithFormat like this:
NSString *document = [NSString stringWithFormat:#"%# %# %# %# %#", description, focus, level, equipment, waterDepth];

You have wrong initialize filename. It should be:
NSString *filename = [NSString stringWithFormat:#"%#/%#", supportDirectory,[_nameTextField.text stringByAppendingString:#".txt"]];
it will works! Good luck:)

The
NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];
is wrong. It should be:
NSString *filename = [NSString stringWithFormat:"%#%#",[_nameTextField.text stringByAppendingString:#".txt"], supportDirectory];

Related

Parsing a JSON text

With the following way...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"/lkj/"]];
NSString *fileName = [NSString stringWithFormat:#"/sandbox/2012_05_11.json"];
[[self restClient] loadFile:fileName intoPath:path];
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:path];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
// getting the data from inside of "menu"
NSString *message = (NSString *) [data objectForKey:#"message"];
NSString *name = (NSString *) [data objectForKey:#"name"];
namegroup.text = [NSString stringWithFormat:#"%# %#",name, message];
...I am trying to parse a document I have previously made with other code...
{"message":["Untitled1a","Untitled2a","Untitled3a"],"name":["Untitled1b","Untitled2b","Untitled3b"]}
with the code above though, in name group.text, this appears...
(untitled, untitled, untitled) (untitled, untitled, untitled)
...but what I would like to do is to allocate many UITextFields, each of them in pairs, (2, 2, 2..), one field which displays the name and the other the message, so pair up 1a with 1b, 2a with 2b... obviously the fields won't be Untitled1a, but "how are you"...
But I can't seem to fix this issue!! Please help!!
You may try something like this:
NSArray *message = [data objectForKey:#"message"];
NSArray *name = [data objectForKey:#"name"];
NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:message forKeys:name];
for (NSString* Key in [Dictionary allKeys]){
NSLog(#"%# %#",Key,[Dictionary objectForKey:Key]);
}

iPad app - generating text file

Can someone explain and give example code to do the following steps in my iPad app:
do some things in my app, which generates some data (as a string)
write that data to a text file
be able to plug in my iPad to my computer and grab those text files off
How can I do this?
For writing string in a file use this
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"data.txt"];
NSError *error;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Then set Application supports iTunes file sharing key to YES in your plist file.
When you connect your device with iTunes from there you can save your data.txt
Here is the video how to get files from iTunes
Edited as requested.
NSUserDefaults *deflt = [NSUserDefaults standardUserDefaults];
//this number file is saved, I'm not saving the file name as data0.txt.
//The first file to be saved is data1.txt
int num = [deflt integerForKey:#"fileNameNum"];
num++;
NSString *fileName = [NSString stringWithFormat:#"data%d.txt",num];;
NSString *str = #"your string";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError *error = nil;
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
//Save the number of the file that you have save in doc directory
[deflt setInteger:num forKey:#"fileNameNum"];
}

How can I read user input text from a textfield and write it to a text file in Xcode?

Is there a way to write a string , which is read from text field, to a .txt file?
NSString *input = [textfield text];
NSString *path = #"myText.txt";
[input writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Yes, ultimately that is the way; but there's a number of other steps you do in order to get from start to finish (you need to have textfield connected to an IBOutlet or in some other way accessible; the path where myText.txt is writing to needs to be writable and therefore you'd probably need to have a longer, more precise path than just the filename; you'd probably need to also send in an actual error parameter that could be set so you could look at the errors being returned when the writeToFile call fails the first few times you run this code).
You will need to define a path, basically where to save the file.
This code will find the Documents folder
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
Here is the code I use to read and write files.
-(void)writeFileToDisk:(id)data
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = #"MyFileName.txt";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
[data writeToFile:fileAndPath atomically:YES];
}
-(void)readFileFromDisk
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = #"MyFileName.txt";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:fileAndPath];
NSLog(#"%#",array);
[array release];
}

Crash on writeToFile

I'm using quite a simple method of storing file names in a text file. For some reason when I initiate the writeToFile I get a crash:
pathString = [NSString stringWithFormat:#"New FileName - %#.png", identifier];
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
NSString *newContents = [NSString stringWithFormat:#"%#:::%#",currentContents, pathString];
NSData *newData = [newContents dataUsingEncoding:NSUTF8StringEncoding];
[newData writeToFile:saveFilePath options:NSDataWritingAtomic error:nil];
It reads the file, places it's contents into a variable called currentContents, then adds the new string to the file, and re-writes it. What's going wrong here.
Without the writeToFile line it works, with it, I get a crash.
Origin of saveFilePath
NSString *saveDocument = [NSString stringWithFormat:#"SavedFile.txt"];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
saveFilePath = [docsDirectory stringByAppendingPathComponent:saveDocument];
An NSLog of saveFilePath reveals a correct path
I think your problem might actually be a missing null character ('\0') at the end of your NSData object. So you finally end up with messed up data. You might want to use -writeToFile:atomically:encoding:error: on your new string right away anyway.
It turns out that the reason the file wasn't writing was because of an unallocated variable:
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
should have been:
NSString *currentContents = [[NSString alloc] initWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];

Objective-C / Can't access (read) file in "Resources" folder

This is probably a very easy problem to solve but i have not succeeded. I have copied the file "questions_famquiz_easy_110326.txt" to the resources folder and now want to access (read) it and NSLog it to see that i am able to read it.
The code below is from one of the tests i have done based on examples that i have found on the web.
I am trying to access a txt-file in the Resources folder and fail to do so. I have searched for a solution, tested a lot, but not succeeded.
I am testing with the following code:
NSLog(#"\n \n >>>>>>viewDidLoad<<<<<<<<<");
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
if(![fileManager fileExistsAtPath:filePath])
{
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/questions_famquiz_easy_110326.txt"]];
[data writeToFile:filePath atomically:YES];
}
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myString: %#", myString);
NSLog(#"\n \n>>>>>>DONE WITH viewDidLoad<<<<<<<<<");
exit(0); //====EXIT JUST FOR THE TEST====<<<
The above code is located in the first viewController that is started.
The output i get is:
>>>>>>viewDidLoad<<<<<<<<<
2011-04-24 21:53:47.825 FamQuiz_R0_1[542:307] myString: (null)
2011-04-24 21:53:51.044 FamQuiz_R0_1[542:307]
>>>>>>DONE WITH viewDidLoad<<<<<<<<<
Could someone nice help me to solve this?
update:
Here is the filePath:
2011-04-24 22:38:08.562 FamQuiz_R0_1[637:307] filePath: /var/mobile/Applications/7F5FDB03-0D22-46BC-91BC-4D268EB4BBEB/FamQuiz_R0_1.app/questions_famquiz_easy_110326.txt
Here is where i have placed the file:
PROBLEM SOLVED:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
When i used the above it did not work, when i used the below it worked and printed out the text.
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
You're not reading from the resources folder. You're trying to read from the document directory. So getting back nil makes sense since the file doesn't exist there.
Change:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:#"questions_famquiz_easy_110326.txt"];
to:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"questions_famquiz_easy_110326" ofType:#"txt"];
and it should work for you.