Save Plain Text to File (Obj-C)
-
30-05-2021 - |
Question
My application (for Mac) generates some HTML... This HTML then needs to be saved to a .html file. I'm trying to use a NSSavePanel like this:
- (IBAction)saveFile:(id)sender{
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setRequiredFileType:@"html"];
[savePanel setTitle:@"Save Code to File"];
if ([savePanel runModal] == NSOKButton)
{
[[_codeStore RTFFromRange:
NSMakeRange(0, [[_codeStore string] length])]
writeToURL:[savePanel URL] atomically:YES];
NSLog(@"saved");
}
}
My problem is that this does not save is a plain text. For example, when I open the generated file in a web browser, the html shows up, but
{\rtf1\ansi\ansicpg1252\cocoartf1157\cocoasubrtf700 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\pardirnatural \f0\fs24 \cf0
is at the top of the page...
Solution
The problem looks to be
[[_codeStore RTFFromRange: NSMakeRange(0, [[_codeStore string] length])]
writeToURL: [savePanel URL]
atomically: YES];
You're outputting an RTF document that contains the HTML. You need
[[_codeStore string] writeToURL: [savePanel URL]
atomically: YES
encoding: NSUTF8StringEncoding
error: nil];
This will take the raw NSString from your NSAttributedString _codeStore
and write that to a file.
OTHER TIPS
i think using rtf encoding is causing the problem since it can write beyond 8 bit using escape sequence. You may try to use simple nsstring way of writing to file.
BOOL ok = [string writeToFile:path atomically:YES
encoding:NSUnicodeStringEncoding error:&error];