Billy Shih
Billy Shih

Reputation: 624

How to correctly escape a % symbol

I'm having trouble getting a string URL to format correctly. The desired output is this:

http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=1&max-results=50&v=2&fields=entry%5Blink/@rel='http://gdata.youtube.com/schemas/2007%23mobile'%5D

This is the code I started with:

NSString *urlRequest = [NSString stringWithFormat:@"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry[link/@rel='http://gdata.youtube.com/schemas/2007%23mobile']", dataStartIndex, dataIncrements];
NSURL *url = [NSURL URLWithString:urlRequest];

It keeps garbling the '%23mobile' at the end and making it '20072obile'. I tried using a \ before the @ symbol but that didn't work. What am I doing wrong?

Strangely, it works correctly if I break it into 2 pieces like this:

NSString *urlRequest = [NSString stringWithFormat:@"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry", dataStartIndex, dataIncrements];

NSURL *url = [NSURL URLWithString:[urlRequest stringByAppendingString:@"[link/@rel='http://gdata.youtube.com/schemas/2007%23mobile']"]];

It also works if I do it without any arguments (dataStartIndex, dataIncrements).

Upvotes: 1

Views: 307

Answers (3)

nhahtdh
nhahtdh

Reputation: 56809

Add an extra % to escape the %, since the string you provided is a format string, not plain string.

Upvotes: 2

Abhishek Singh
Abhishek Singh

Reputation: 6166

You can use :-

NSString *string=[@"yourUrlString" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Upvotes: 2

mttrb
mttrb

Reputation: 8345

You need to escape the %23 with another %, to make 2007%%23mobile. For example:

NSString *urlRequest = [NSString stringWithFormat:@"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry[link/@rel='http://gdata.youtube.com/schemas/2007%%23mobile']", dataStartIndex, dataIncrements];

Upvotes: 2

Related Questions