Reputation: 4313
I have the following code:
return (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(";:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
Xcode says it is deprecated in iOS 9. So, how do I use stringByAddingPercentEncodingWithAllowedCharacters ?
Thanks!
Upvotes: 9
Views: 12380
Reputation: 133239
The character set URLQueryAllowedCharacterSet
contains all characters allowed in the query part of the URL (..?key1=value1&key2=value2
) and is not limited to characters allowed in keys and values of such a query. E.g. URLQueryAllowedCharacterSet
contains &
and +
, as these are of course allowed in query (&
separates the key/value pairs and +
means space), but they are not allowed in a key or a value of such a query.
Consider this code:
NSString * key = "my&name";
NSString * value = "test+test";
NSString * safeKey= [key
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * safeValue= [value
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * query = [NSString stringWithFormat:@"?%@=%@", safeKey, safeValue];
query
will be ?my&name=test+test
, which is totally wrong. It defines a key named my
that has no value and a key named name
whose value is test test
(+ means space!).
The correct query would have been ?my%26name=test%2Btest
.
As long as you only deal with ASCII strings or as long as the server can deal with UTF-8 characters in the URL (most web servers today do that), the number of chars you absolutely have to encode is actually rather small and very constant. Just try that code:
NSCharacterSet * queryKVSet = [NSCharacterSet
characterSetWithCharactersInString:@":/?&=;+!@#$()',*% "
].invertedSet;
NSString * value = ...;
NSString * valueSafe = [value
stringByAddingPercentEncodingWithAllowedCharacters:queryKVSet
];
Upvotes: 18
Reputation: 976
Another solution to encode those characters allowed in URLQueryAllowedCharacterSet
but not allowed in a key or a value (e.g.: +
):
- (NSString *)encodeByAddingPercentEscapes {
NSMutableCharacterSet *charset = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[charset removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
NSString *encodedValue = [self stringByAddingPercentEncodingWithAllowedCharacters:charset];
return encodedValue;
}
Upvotes: 8
Reputation: 2617
try this
NSString *value = @"<url>";
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Upvotes: 24