Saving and loading multiple strings to a UITextView in iOS - 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.

Related

How to store a NSData locally

I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this
NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"the converted string to nsdata is :%#",conData);
[conData writeToFile:#"Filename.txt" atomically:YES];
but unfortunately this is not working can any one help.
Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.
This writes file for me
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Filename.txt"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
you should pass a correct path in writeToFile method
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];
You have given only file name(Filename.txt) not whole file path thats why your code is not working.
Check below line of code you will get idea.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];

How to create a .txt file programmatically on iOS

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.
Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.
NSError *error;
NSString *stringToWrite = #"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
And to retrieve the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
I hope this help's you
-(void)writeToTextFile{
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:#"%#/filename.txt",
documentsDirectory];
NSString *content = #"This is Demo";
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)ShowContentlist{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
[content release];
}

ipad - write NSString to text file

I have text file text.txt in my xcode project and I need to write NSString init from my iOS app. I've tried this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: #"text.txt"];
NSString *content = #"Test";
[content writeToFile: docFile atomically: NO];
But it doesn't work for me... So can you help me with it?
this worked for me
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
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:#"%#/text.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = #"Test";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}

iOS: How to save text from UITextBox to file

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.

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.

Resources