Cfurlcreatestringbyaddingpercentescapes Is Deprecated in iOS 9, How to Use "Stringbyaddingpercentencodingwithallowedcharacters"

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

try this

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

Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

The deprecation message says (emphasis mine):

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

So you only need to supply an adequate NSCharacterSet as argument. Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSet that you can use like this:

let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Update for Swift 3 -- the method becomes the static property urlHostAllowed:

let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Be aware, though, that:

This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.

String won't url encode in iOS

For future reference, this is what I found to work (i.e. encode everything properly)

+ (NSString*)encodeURL:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

if (newString)
{
return newString;
}

return @"";
}


Related Topics



Leave a reply



Submit