简体   繁体   中英

'CFURLCreateStringByAddingPercentEscapes' deprecated in STTwitter Library

I'm using the STTwitter Library in my App and it's been throwing a deprecation warning that says the following:

 '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. 

Here's the code that is causing the problem in STTwitter:

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

    NSString *s = (__bridge_transfer NSString *)(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                         (CFStringRef)self,
                                                                                         NULL,
                                                                                         CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                                         kCFStringEncodingUTF8));
    return s;
}
@end

The question is how to replace this with equivalent code using 'stringByAddingPercentEncodingWithAllowedCharacter'.

Here's valid replacement code:

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

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

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

I've tested the new code verses the old and in all cases, thus far, the strings they generate are equal.

In the original code, the idea was to escape a specific named set of characters. They were:

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

When you switch to using 'stringByAddingPercentEncodingWithAllowedCharacters', the logic reverses and only characters not named are escaped. So, the new code specifies 'alphanumericCharacterSet' and a small group of additional characters are added to it. The added characters are:

-._~

Those characters not named in the new code are the same set set of characters explicitly named in the old code..

As an aside, it is not clear to me that that the passed encoding parameter in the original code was ever used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM