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
iOS UIlabel Autoshrink So Word Doesn't Truncate to Two Lines
Collide Type Source Error - Spritekit Swift Game
Notification in Swift Every Day at a Set Time
iOS - Combine/Concatenate Multiple Audio Files
Are Private Frameworks Supported on iOS
How to Make a Phonegap App for iOS Without Mac
How to Add a Lock Screen Widget (Requiring iOS 16) and Still Support iOS 15
Converting String to Nsdate Giving Wrong Date
Bootstrap Columns with Flexbox Are Not Taking Proper Width on iOS and Safari
How to Fix Broken Transform-Origin on iOS11 and Macos10.12 Safari
Save The Exif Metadata Using The New PHPhotolibrary
Creating a First Launch Viewcontroller
How to Use The Coreaudio API in Swift
Resize All Subview in Scrollviewdidzoom
How Has The Nsindexpath Initialization Changed in Swift3
Urlsession.Shared.Datatask VS Datataskpublisher, When to Use Which