'CFURLCreateStringByAddingPercentEscapes is deprecated in iOS 9, how do I use "stringByAddingPercentEncodingWithAllowedCharacters"

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!



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 qfwfq