Ampersand cutting off NSString?

Discussion in 'Mac Programming' started by kwjohns, Apr 8, 2009.

  1. macrumors 6502a


    Jul 4, 2007
    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.
  2. Moderator emeritus


    Jun 15, 2000
    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:@"", (NSString *)encodedBody];
    NSURL *url = [NSURL URLWithString:urlString];
  3. thread starter macrumors 6502a


    Jul 4, 2007
    That did the trick. Thank you very much!

Share This Page