CFURLCreateStringByAddingPercentEscapes is deprecated in iOS 9, how do I use “stringByAddingPercentEncodingWithAllowedCharacters”

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

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!

回答1:

try this

NSString *value = @""; value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; 


回答2:

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


回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!