-4

Right, I've seen solutions like this before, but nine that seem to do the trick. I want to save text from a Text Field into a file in Supporting Files.

Preferably, I want it to be an HTML file, and I want it there because I want to open it again in a Web View.

I know how to do the loading, its just the saving.

The question: How do I save text from a Text Field into a file inside the Supporting Files directory?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user2333270
  • 17
  • 1
  • 4

2 Answers2

0

Try something like this:

- (void)writeStringToFile:(NSString*)aString {

    // Build the path, and create if needed.
    NSString *theString = @"The text to write";
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:@"data.txt"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }
    [[theString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
woz
  • 10,888
  • 3
  • 34
  • 64
  • For some reason, neither ways work. Nothing happens; no file is created / written to (even if made previously). Am I missing something? – user2333270 May 11 '13 at 17:04
0

Problem Solved (HTML) !!!

try this code,

NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentDirectory stringByAppendingPathComponent:@"myfile.html"];

NSString *textFromTextField = textField.text;
NSString *finalText = [NSString stringWithFormat:@"<html><body>%@</body><html>",textFromTextField];

[finalText writeToFile:@"" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Thilina Chamath Hewagama
  • 9,039
  • 3
  • 32
  • 45