iOS: How to save text from UITextBox to file - ios

I want to save a text string from a file when a user presses a button. Could this file be a .plist? Then, later, I want another function to read the text from the file and turn it into a variable. How is this possible?
Snarky

Saving:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingString:#"/myFile.plist"];
//Create the file if it doesnt exists
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
NSDictionary *emptyDic = [NSDictionary dictionary];
[emptyDic writeToFile:path atomically:YES];
}
//Save the text using setObject for key or something similar, you could even use a NSArray instead
NSDictionary *dic = [[NSDictionary alloc]init];
[dic writeToFile:path atomically:YES];
Loading:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/myFile.plist", documentsDirectory];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
I think you can't use a .txt file directly but I have never tried it.

If you just want to save some user default setting for future reference, check out NSUserDefaults. Easier than dealing with files if you're really just trying to save some setting.
If you really want to read a string from a file, go to your Xcode organizer, go to documentation, click on the search icon, and type in "Reading Strings From" and one of the top links will be how to read and write to files.

Related

NSDocumentDictionary: Saving NSString as file for Russian characters

I have an editable uitextview in which the user types in Russian or English. I then save this text as a .txt file in the files directory, and read it later.
Here is the portion to save the text
-(IBAction)saveText:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"testing.txt"];
[self.textBox.text writeToFile:path atomically:YES];
NSLog(path);
}
There is a separate button to display this text in a popover:
-(IBAction)readText:(id)sender{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"testing.txt"];
NSError *error = nil;
myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myText: %#", myText);
self.textBox.text= myText;
}
with this declaration in the .h file
NSString *myText;
it works fine if I only type English, but if I type Russian characters then nothing saves/displays.
So, say I type "hello" it works, but ifI then type " some Russian phrase " to append self.textBox.text it doesn't work.
How can I make this Russian (or UTF8/charcode) compatible?
writeToFile:atomically: is deprecated and writes the string in the default encoding
(whatever that is, probably MacRoman). Better use
[self.textBox.text writeToFile:path
atomically:NO
encoding:NSUTF8StringEncoding
error:&error];
to write the string UTF-8 encoded.

Why can't I save files to my iOS apps /Documents directory?

I am writing an app that can access the iOS root system, the user should be able to save files to his document directory. I am using this code to save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for example .plist files with the save text methods, the contact is replaced by the directory path of the file. When I save a picture, or any other file it isn't readable. Is there a good method to save files without destroying them?
You're calling [self.filePath writeToFile:], thus writing the contents of the filePath variable to a file.
You should do something like:
[contents writeToFile:...]
Here you have an example of saving the image:
assuming you get the content of the image into NSData object:
NSData *pngData = UIImagePNGRepresentation(image);
then write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Have a look into these questions for more detailed explanations:
Write a file on iOS
Save An Image To Application Documents Folder From UIView On IOS

Saving and loading multiple strings to a UITextView in iOS

I'm working on an app that's a bit like a notebook of typed pages.
I have a UITextView *documentText and an int currentPage to keep track of multiple pages. Back and forward buttons add 1 or subtract 1 from currentPage and then they set the text in documentText to match the new value of currentPage.
However, when I run it, nothing saves, there's just a blank text field. I think it's a problem with [saveDocs writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:NULL];
, but I'm not sure what to change, or if that's even the problem.
Anyways, here's the code I'm using to save the text:
- (IBAction)saveDocs:(id)sender {
NSString *saveDocs = documentText.text;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#-%d.txt", #"document", currentPage]];
[saveDocs writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:NULL];
[[NSUserDefaults standardUserDefaults] setInteger:currentPage forKey:#"CurrentDocument"];
}
Also, in ViewDidLoad, I'm using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
currentPage = [[NSUserDefaults standardUserDefaults] integerForKey:#"CurrentDocument"];
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#-%d.txt", #"document", currentPage]];
NSString* doc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[documentText setText:doc];
Thanks for your help,
-Karl
You write with NSUnicodeStringEncoding. But you read with NSUTF8StringEncoding. Perhaps you should stick with NSUTF8StringEncoding for both writing and reading.

Writing data into file

I'm trying to make a txt log file with the actions that happens in my app. I want to save some text whenever the app is connecting to the server o displaying new info.
Well, how do I write to a file? I've tried using the method writeToFile: but it's not working because fileExistsAtPath: is returning NO.
My code is:
NSString *file_path = #"mylog.txt";
NSString *log = #"Hello World!!\n";
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
Thanks!
PS: Oh, would it be readable through Organizer with the iPhone plugged in?
You should use the < App_Home >/Documents folder for storing Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file_Path = [documentsDirectory stringByAppendingPathComponent:#"log.txt"];
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
But normally if you want to see and dump things while running the app,
you could just use NSLog() which outputs it in the console.
Try this method I wrote:
+(NSString*)createPath:(NSString*)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localizedPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
//NSLog(#"%#",localizedPath);
return localizedPath;
}
It will return you a path for your file. You only need to give it a name.

Trying to encrypt an NSDictionary when writing to file

I'm currently saving an NSDictionary to file on the iOS device. However, NSDictionary files are readable XML. I don't want people to be able to get in and read the contents so I need to be able to encrypt the file on writing and decrypt when loading it back again.
I'm currently saving the file like this:
NSFileManager* fileManager = [NSFileManager defaultManager];
if (!fileManager)
{
NSLog(#"Failed to get file manager to save.");
return;
}
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"save.dic"];
[m_dictionary writeToFile:filePath atomically:YES];
And I'm loading the dictionary like this:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"save.dic"];
m_dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
Can anyone tell me a nice way of encrypting\decrypting this?
Cheers,
Rich
Use a NSKeyedArchiver to create an NSData object from your dictionary (NSKeyedArchiver archivedDataWithRootObject:). Then encrypt the NSData with AES and write that to your file.
Reading takes the reverse: first, read the NSData, decrypt it via the method from the mentioned link, then pass the decrypted NSData to NSKeyedUnarchiver (NSKeyedUnarchiver unarchiveObjectWithData:) and you get your dictionary back.

Resources