我在我的应用程序中使用STTwitter库并且它已经抛出了一个弃用警告,其中包含以下内容:
'CFURLCreateStringByAddingPercentEscapes' is deprecated: first deprecated
in iOS 9.0 - Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:]
instead, which always uses the recommended UTF-8 encoding, and which encodes
for a specific URL component or subcomponent (since each URL component or
subcomponent has different rules for what characters are valid).' deprecated
error.
这是导致STTwitter问题的代码:
@implementation NSString (RFC3986)
- (NSString *)st_stringByAddingRFC3986PercentEscapesUsingEncoding:(NSStringEncoding)encoding {
NSString *s = (__bridge_transfer NSString *)(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8));
return s;
}
@end
问题是如何使用' stringByAddingPercentEncodingWithAllowedCharacter'来替换等效代码。
答案 0 :(得分:0)
这是有效的替代代码:
@implementation NSString (RFC3986)
- (NSString *) st_stringByAddingRFC3986PercentEscapesUsingEncoding: (NSStringEncoding) encoding {
NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
[allowed addCharactersInString: @"-._~"];
return( [self stringByAddingPercentEncodingWithAllowedCharacters: allowed] );
}
@end
我已经测试了旧代码和旧代码,在所有情况下,到目前为止,它们生成的字符串是相同的。
在原始代码中,想法是转义特定的命名字符集。他们是:
!*'();:@&=+$,/?%#[]
当您切换到使用'stringByAddingPercentEncodingWithAllowedCharacters'时,逻辑会反转,只有未命名的字符才会被转义。因此,新代码指定了'alphanumericCharacterSet',并添加了一小组附加字符。添加的字符是:
-._~
新代码中未命名的那些字符与旧代码中明确命名的字符集相同。
顺便说一下,我不清楚原始代码中传递的编码参数是否被使用过。