2

I am creating a URL string like so:

[Items appendString:[object objectForKey:@"Items"]]; [Items appendString:@"*"]; [Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)]; //This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT //add Items to URL NSString *fullURL = [NSString stringWithFormat:@"https://example.com?Items=%@, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

but it returns like so:

Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT 

how do I get it return like this:

%20%26%20 instead of %20&%20 for the & ?

1
  • why don't you use NSMutableURL? Commented May 12, 2015 at 13:38

3 Answers 3

2

I think the issue is that the method tries to be too clever - it only does as much as is necessary to get a legal URL and because you don't have a question mark in your string, it probably thinks it is OK to leave the ampersands in.

Try constructing the whole URL and do the escaping on the whole URL.

NSString *fullURL = [[@"https://example.com?Items=" stringByAppendingString: items] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

Or perhaps use stringByAddingPercentEncodingWithAllowedCharacters:.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this.

fullURL=[fullURL stringByReplacingOccurrencesOfString:@"&" withString:@"%26"]; NSLog(@"fullURL: %@ ...", fullURL); 

Comments

0

Use CFURLCreateStringByAddingPercentEscapes() for getting UTF8stringencoding of characters

NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.