Search code examples
iphonecocoa-touchnsstringurl-encoding

How to handle '&' in URL sent as HTML from iPhone Mail.app


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&age=53&mate=sid%20vicious">view</a>

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!


Solution

  • 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 &.