Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

kwjohns

macrumors 6502a
Original poster
Jul 4, 2007
700
12
I have an NSString with an ampersand (&) in it being sent to the Mail app and it keeps cutting off the rest of my string. I've tried looking for a solution and using &&, %& and /ampersand but none seem to work. This is making me pull my hair out!

Edit: This should have gone into the iPhone forum but I'm sure the issue is the same.
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
You need to encode the & since normally it's used to separate parameters in the URL. Normally NSString's stringByAddingPercentEscapesUsingEncoding method would work in most cases, but here you need to use Core Foundation to encode the ampersand:

Code:
NSString *body = @"This is an ampersand & test.";
CFStringRef encodedBody = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)body, NULL, CFSTR("&"), kCFStringEncodingUTF8);
NSString *urlString = [NSString stringWithFormat:@"mailto:user@domain.com?body=%@", (NSString *)encodedBody];
CFRelease(encodedBody);
NSURL *url = [NSURL URLWithString:urlString];
 

kwjohns

macrumors 6502a
Original poster
Jul 4, 2007
700
12
You need to encode the & since normally it's used to separate parameters in the URL. Normally NSString's stringByAddingPercentEscapesUsingEncoding method would work in most cases, but here you need to use Core Foundation to encode the ampersand:

Code:
NSString *body = @"This is an ampersand & test.";
CFStringRef encodedBody = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)body, NULL, CFSTR("&"), kCFStringEncodingUTF8);
NSString *urlString = [NSString stringWithFormat:@"mailto:user@domain.com?body=%@", (NSString *)encodedBody];
CFRelease(encodedBody);
NSURL *url = [NSURL URLWithString:urlString];

That did the trick. Thank you very much!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.