views:

185

answers:

1

I'm attempting to take an NSImage and convert it to a string which I can write in an XML document.

My current attempt looks something like this:

[xmlDocument setCharacterEncoding: @"US-ASCII"];

NSData* data = [image TIFFRepresentation];
NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

//Put string inside of NSXMLElement, write out NSXMLDocument.

Reading back in looks something like this:

NSXMLDocument* newXMLDocument = [[NSXMLDocument alloc] initWithData:data options:0 error:outError];
//Here's where it fails. I get:
//Error Domain=NSXMLParserErrorDomain Code=9 UserInfo=0x100195310 "Line 7: Char 0x0 out of allowed range"

I assume I'm missing something basic. What's up with this encoding issue?

+1  A: 

First of all, embedding large amounts of binary data in XML is not a good idea, IMHO.

To answer your question, you need an encoding scheme that supports binary data, such as Base64.

See this page for more than one way to represent arbitrary NSData as a Base64-encoded string: http://www.cocoadev.com/index.pl?BaseSixtyFour

UPDATE: The link to Colloquy's NSData additions seems to be broken on that page. Here's the new URL: http://colloquy.info/project/browser/trunk/Additions/NSDataAdditions.m

Can Berk Güder
Great solution! From totally troubled to fully functional in 11 minutes. :)Also, yes, this a temporary thing; I'm aware it's ugly.
andyvn22