2012-05-24 27 views
1

我無法正確地格式化字符串URL。所需的輸出是這樣的:如何正確轉義%符號

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 

這是我開始的代碼:

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]; 

它使錯亂的「%23mobile」末,使之「20072obile」。我在@符號前嘗試使用\,但沒有奏效。我究竟做錯了什麼?

奇怪的是,它工作正常,如果我打破它分爲2個這樣的:

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']"]]; 

如果我不帶任何參數(dataStartIndex,dataIncrements)它也適用。

回答

2

您需要跳過%23與另一個%,使2007%%23mobile。例如:

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]; 
2

因爲您提供的字符串是一個格式字符串,而不是純字符串,所以添加一個額外的%來轉義%。

2

您可以使用: -

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