views:

37

answers:

2

Hi there,

In my iPhone App I have the capability to export data to an .txt file and send it via Mail – but have currently problems regarding the encoding.

To attach the file to mail I simply create a NSData instance from a NSString instance as followed:

NSData *dataToExport = [[NSData alloc] initWithData:[myExportString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSFileManager defaultManager] createFileAtPath:pathToExportFile contents:dataToExport attributes:nil];

But this finally results in a file with content like that (wrong encoding):

√úberraschung

Instead using

[myExportString writeToFile:pathToExportFile atomically:NO encoding:NSUTF8StringEncoding error:&error];

... creates a file with the correct enconding:

Überraschung

Any ideas, how I'm able to get the right encoding with the first way?

Thank you, Florian

A: 

Hi Jeremy,

That's strange. Here ist the hexdump -C output.

"Wrong" encoding:

00000000  c3 9c 62 65 72 72 61 73  63 68 75 6e 67           |..berraschung| 
0000000d

"Right" encoding:

00000000  c3 9c 62 65 72 72 61 73  63 68 75 6e 67           |..berraschung|
0000000d

I'm also trying different applications to view the documents:

  • TextEdit: wrong
  • Excel: wrong
  • SubEthaEdit: right
  • Numbers: right

Very strange,right?

Florian Mielke
A: 

NSString's writeToFile:atomically:encoding:error: method sets an extended attribute on the output file identifying the encoding. TextEdit checks for this attribute and uses that encoding when it's present.

Since you don't (and can't) tell NSFileManager's method what encoding to use (since it's for plain data, not necessarily text encoded as data), it won't set this attribute. Without it, TextEdit will guess, and it does so quite poorly.

I don't know whether MobileMail will preserve the extended attribute somehow. Try it both ways, and when you receive the messages, check their raw contents and see whether one of them specifies the file's encoding. At any rate, your hex dumps prove that the text is being encoded correctly either way.

More generally, when you want to write out text to a file, NSString's methods are the correct solution.

Peter Hosey
Thank you for that explanation. I'll check your suggestion.
Florian Mielke