views:

224

answers:

2

Apologies if this has been answered already. There are similar topics but none that I could find pertaining to Cocoa & NSStrings...

I'm constructing a clickable URL to embed in an HTML email to be sent via the MFMailComposeViewController on the iPhone. i create the url then use stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding to polish up white space, etc. then add some surrounding HTML to get:

<a href = "http://www.site.com/viewitem?name=Johnny%20Rotten&amp;age=53&amp;mate=sid%20vicious"&gt;view&lt;/a&gt;

All's well so it's appended to emailBody. However once [mailComposer setMessageBody:emailBody isHTML:YES] all the & become &amp; which isn't ideal within my URL.

can i control this? is there a better encoding algorithm? my HTML is a bit rusty perhaps I'm using the wrong encoding? I'm sure on the server I could parse the &amp; back into & but looking for the Cocoa way...

Thanks!

+2  A: 

Actually, & should always be encoded as &amp; in HTML attributes. Including links. Including form value delimiters. So it's done exactly what you want, even though you didn't know you wanted it.

Look at it this way: in your URL, you have &age=53... That's interpreted first as a character entity, and only after that doesn't work is it interpreted as an ampersand followed by more character data.

The W3C spec is quite clear on this:

Authors should use "&amp;" (ASCII decimal 38) instead of "&" to avoid confusion with the beginning of a character reference (entity reference open delimiter). Authors should also use "&amp;" in attribute values since character references are allowed within CDATA attribute values.

That should settle it: use &amp; not &.

Steven Fisher
Meltemi
Steven Fisher
updated answer to include example and link to W3C spec.
Steven Fisher
@Meltemi - so long as you use an HTML parser, it will "just work". You only get problems if you start trying to do things like extract the URL by treating the HTML as some text you run regular expressions over.
David Dorward
A: 

Are you calling MFMailComposeViewController's

setMessageBody:isHTML:

and what do you set isHTML to?

Depending on it's setting it might very well be that MFMailComposeViewController is trying to help you out be encoding the entire message body...

Either don't encode the body yourself or make the entire body HTML.

Niels Castle
it's mentioned above but I'm using isHTML:YES
Meltemi