1

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

Gallymon
  • 1,557
  • 1
  • 11
  • 21

1 Answers1

1

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.

Gallymon
  • 1,557
  • 1
  • 11
  • 21