PDA

View Full Version : Ampersand cutting off NSString?




kwjohns
Apr 8, 2009, 02:12 PM
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
Apr 8, 2009, 02:42 PM
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:

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
Apr 8, 2009, 03:04 PM
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:

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!