Encoding and Decoding URL Data

To percent-encode part of a URL string, use the NSString method stringByAddingPercentEncodingWithAllowedCharacters:, passing the appropriate character set for the URL component or subcomponent:

For example, to percent-encode a UTF-8 string for inclusion in a URL fragment, you do the following:

NSString *originalString = @"color-#708090";
NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];
NSString *percentEncodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"%@", percentEncodedString"); // prints "color-%23708090"
let originalString = "color-#708090"
let allowedCharacters = NSCharacterSet.urlFragmentAllowed
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
print(encodedString!) // prints "color-%23708090"

If you want to decode a percent-encoded URL component, use NSURLComponents to split the URL into its constituent parts and access the corresponding property.

For example, to get the UTF-8 string value for a percent-encoded URL fragment, you do the following:

NSURL *URL = [NSURL URLWithString:@"https://example.com/#color-%23708090"];
NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
NSString *fragment = components.fragment;
NSLog(@"%@", fragment); // prints "color-#708090"
let url = URL(string: "https://example.com/#color-%23708090")!
let components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
let fragment = components.fragment!
print(fragment) // prints "color-#708090"