1

我在我的应用程序中使用 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”将其替换为等效代码。

4

1 回答 1

0

这是有效的替换代码:

@implementation NSString (RFC3986)
- (NSString *) st_stringByAddingRFC3986PercentEscapesUsingEncoding: (NSStringEncoding) encoding {

   NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
   [allowed addCharactersInString: @"-._~"];

   return( [self stringByAddingPercentEncodingWithAllowedCharacters: allowed] );
   }    
@end

我已经测试了新代码和旧代码,并且在所有情况下,到目前为止,它们生成的字符串都是相等的。

在原始代码中,想法是转义一组特定的命名字符。他们是:

!*'();:@&=+$,/?%#[]

当您切换到使用“stringByAddingPercentEncodingWithAllowedCharacters”时,逻辑反转,只有未命名的字符被转义。因此,新代码指定了“alphanumericCharacterSet”,并添加了一小组附加字符。添加的字符是:

-._~

新代码中未命名的字符与旧代码中明确命名的字符集相同。

顺便说一句,我不清楚原始代码中传递的编码参数是否曾被使用过。

于 2017-04-19T11:38:39.563 回答