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

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

Related

After Update, App Doesn't Load Existing Files from Documents Folder

I'm having an issue with loading existing images from the App's Documents Folder after ad-hoc update.
I've searched the internet for answers and I've found that I must use relative paths to files in order for the path to remain the same when the App is updated.
Can someone please show me how to do it ?
Right now I use the following to save the files (images) when ImagePicker finishes:
NSString *imageFilename = [NSString stringWithFormat:#"%#-profilePhoto.jpg",[NSDate date]];
NSArray *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
imagePath = [NSString stringWithFormat:#"%#/%#", paths, imageFilename];
Please help me out !
I've found the solution:
Instead of loading the images from the full path, I chose to make the system search for them after their name.
So instead of:
//Full path stored in a dictionary:
profilePhotoPath = [userDict objectForKey:#"profilepic"];
//Load the image from path:
profilePhoto = [[UIImage alloc] initWithContentsOfFile:profilePhotoPath];
I now use the following:
//Load image from documentsDirectory, filename
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
profilePhotoPath = [userDict objectForKey:#"profilepic"];
profilePhotoPath = [documentsDirectory stringByAppendingPathComponent:[profilePhotoPath lastPathComponent]];
profilePhoto = [[UIImage alloc] initWithContentsOfFile:profilePhotoPath];
By using "lastPathComponent" attribute I'm basically stripping out everything from the path except the filename and then I use NSSearch to give me my file.
This line makes the problem
NSArray *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Here the issue is the variable paths is of type NSArray not NSString
Change it to,
NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
or
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *paths = [path objectAtIndex:0];

Write NSMutableArray to plist not working

I am using plists to save/load an NSMutableArray,
the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *prsPath = [documentsDirectory stringByAppendingPathComponent:#"records.plist"];
prs = [[NSMutableArray alloc] initWithContentsOfFile:prsPath];
when I am using the last sentence of code somewhere else in my code it says: "prsPath" undeclared. (I am loading my code in ViewDidLoad) When I add an Object it doesn't save it, it doesn't even show up. (Loading the last sentence on add)
I'm using this method and it's work 100%
- (void) writeToPlist: (NSString*)fileName withData:(NSMutableArray *)data
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:finalPath atomically: YES];
/* This would change the firmware version in the plist to 1.1.1 by initing the NSDictionary with the plist, then changing the value of the string in the key "ProductVersion" to what you specified */
}
and this method for reading from plist file:
- (NSMutableArray *) readFromPlist: (NSString *)fileName {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:finalPath];
if (fileExists) {
NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
return arr;
} else {
return nil;
}
}
Hope it can help you.
[[NSMutableArray alloc] initWithContentsOfFile:prsPath] will load a plist ant initialize an array with it. Does you plist exist at that path already? You might also want to log the prsPath to see if it's correct.
Usually you would first check to see if a plist exists at the path by calling [[NSFileManager defaultManager] fileExistsAtPath:prsPath]. If it does not, you initialize an empty array.
Later you save it by calling [prs writeToFile:prsPath atomically:YES].
Note that you can't initialize NSMutableArrays from plists. Arrays and dictionaries loaded from plists are always immutable. You would have to first load the plist into an NSArray and then initialize an NSMutableArray from that NSArray.

How to save text/data in cocoa/xcode to a file?

i'm sorry for the obvious question, but is there something i should be careful about when writing data to a file, because my program can read the data it just wrote, while the program is running, but the moment i stop it, the files become empty
tried using NSFileHandle, in order to write data with it, and close the file later, didn't help... currently, i'm using:
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:newArray];
[encodedObject writeToFile:string atomically:YES];
and no matter what i do, i can't get the simplest NSString to stay in the file permanently
what do i do?
Thanks #LetzFlow, but it didn't solve it just yet.
Now, i'm using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
string = [NSString stringWithFormat:#"%d.rtf",fileName];
NSString *file = [documentsDirectory stringByAppendingPathComponent:string];
//NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:file];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:newArray];
[encodedObject writeToFile:file atomically:YES];
//[fileHandle writeData:encodedObject];
//[fileHandle closeFile];
NSLog(#"%#",[NSString stringWithContentsOfFile:file encoding:NSStringEncodingConversionAllowLossy error:nil]);
to serialize an array of objects, and it the NSLog shows a valid array. Yet, when I look at the file later, or try to unserialize the array (like this):
NSString *stringX = [NSString stringWithFormat:#"%d.rtf",fileName];
NSData *encodedObjectX = [NSData dataWithContentsOfFile:stringX];
NSArray *newArrayX = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObjectX];
TurnigButton *button = [[newArrayX objectAtIndex:1] objectAtIndex:5];
NSLog(#"%d", button.idNum);
it just prints (null). (when they execute one after the other in a single run, it unserializes just fine)
I appreciate the help.
The question is WHERE do you write your file? Because you are not allowed to write files all over the system in iOS.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
The documents directory is usually a place were you can write files, so you might want to give that a try.

write NSString to file

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

NSMutable Array to XML file

I have an NSMutableArray of custom objects called Clip. Each clip Object has some NSString properties (clipName,tcIn, tcOut, file path and so on..). How do I write an xml File on disk where each clip in the array is a node of the xml file and its properties are elements of the node?
Thanks in advance
Dario
I think this is what should do you:
//Create xml string
NSMutableString *xmlString = [[NSMutableString alloc] init];
//Add all the data to the string
[xmlString appendFormat:#"<clips>"];
for (Clip *c in clipsArray)
{
[xmlString appendFormat:#"\n\t<clip>"];
[xmlString appendFormat:#"\n\t\t<clipName>%#</clipName>", c.clipName];
[xmlString appendFormat:#"\n\t\t<tcIn>%#</tcIn>", c.tcIn];
...
[xmlString appendFormat:#"</clip>"];
}
[xmlString appendFormat:#"</clips>"];
//Create a variable to represent the filepath of the outputted file
//This is taken from some code which saves to an iPhone app's documents directory, it might not be ideal
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:#"output.xml"];
//Actually write the information
NSData *data = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];